[英]How to add object to collection inside another collection in MongoDB using Node.js
我知道如何使用Node.js在MongoDB中將對象添加到集合中,例如:
router.post('/addProduct', function (req, res) {
Partner.findByIdAndUpdate({ _id: req.body.partnerId }, { $push: { "products": { name: req.body.dataProduct.name } } }, { safe: true }, function (err, response) {
if (err) throw err;
res.json(response);
});
});
但如果產品會是另一張桌子怎么辦? 我怎樣才能簡單地在那里添加對象?
讓我們說這是我的架構:
var partnerSchema = new mongoose.Schema({
name: String,
products: [
{
name: String,
campaignList: [
{
name: String,
type: String,
startDate: Date,
endDate: Date,
paymentMethod: String,
partnerPayout: Number,
ourPayout: Number
}
]
}]
});
每個partner
和product
中的ID都是默認值._id
例如。 partner._id
和product._id
。 這就是為什么不在上面的架構中。 然而我將它們從FrontEnd發送到BackEnd作為req.parameter
- 通常是我想說的肯定:)
您最好的選擇是打賭自己定義廣告系列的架構和模型,然后使用_id
將其添加到合作伙伴
var partnerSchema = new mongoose.Schema({
name: String,
products: [
{
name: String,
campaignList: [
{ type : mongoose.Schema.Types.ObjectId, ref : 'campaignModel' }
]
}]
});
var campaignSchema = new mongoose.Schema({
name: String,
type: String,
startDate: Date,
endDate: Date,
paymentMethod: String,
partnerPayout: Number,
ourPayout: Number
});
var campaignModel = mongoose.model('campaignModel', campaignSchema);
var partnerModel = mongoose.model('partnerSchema', partnerSchema);
一個好的做法是查找您嘗試嵌套半復雜數據的時間,或者具有兩個或三個以上鍵的對象,並將它們提取到自己的集合中。 它不僅可以更輕松地搜索這些文檔,還可以更輕松地將它們與其他對象結合使用。
一定要在查詢期間調用.populate()
,以便MongoDB知道嵌套來自其他集合的文檔,否則,你將只有一個ObjectId
數組。
首先匹配所需的產品陣列位置。 您可以通過測試一個簡單的查找來確認:
Partner.find({_id: req.body.partnerId), 'products.name': req.body.dataProduct.name }, { 'products.$': 1})
使用位置$運算符將新對象推送到匹配的product元素中的數組中:
Partner.update({_id: req.body.partnerId), 'products.name': req.body.dataProduct.name }, { $push: { 'products.$.campaignList': { name: 'new campaign' }}})
參考https://docs.mongodb.com/manual/reference/operator/update/positional/
嘗試這個:
router.post('/addProduct', function (req, res) {
Partner.findOneAndUpdate({ _id: req.body.partnerId }, { $push: { "products": { name: req.body.dataProduct.name, $push: {"campaignList": {name: req.body.name}} } } }, { safe: true }, function (err, response) {
if (err) throw err;
res.json(response);
});
});
我希望它可以幫助你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.