如何使用Node.js将对象添加到MongoDB中另一个集合中的集合

我知道如何使用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 } ] }] }); 

每个partnerproduct ID都是默认的。 partner._idproduct._id 。 这就是为什么不在上面的模式。 不过,我把它们从前端发送到后端作为req.parameter – 通常的事情,但我想说的确实:)

您最好的select是赌自己定义活动的模式和模型,并使用_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); 

一个好的做法是查找你试图嵌套半复杂数据的时间,或者查找多于两个或三个键的对象,并将它们提取到它们自己的集合中。 这不仅使得search这些文档变得更加容易,而且使其与其他对象结合使用更加容易。

一定要在查询过程中调用.populate() ,以便MongoDB知道从其他集合中嵌套文档,否则只需要一个ObjectId数组。

首先匹配所需的产品arrays位置。 你可以通过testing一个简单的发现来确认这个:

 Partner.find({_id: req.body.partnerId), 'products.name': req.body.dataProduct.name }, { 'products.$': 1}) 

使用位置$操作符将新对象推入匹配的产品元素中的数组:

 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); }); }); 

我希望它可以帮助你