DiP*_*Pix 7 javascript mongodb 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);
});
});
Run Code Online (Sandbox Code Playgroud)
但如果产品会是另一张桌子怎么办?我怎样才能简单地在那里添加对象?
让我们说这是我的架构:
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
}
]
}]
});
Run Code Online (Sandbox Code Playgroud)
在每个ID partner和product是默认._id例如.partner._id和product._id.这就是为什么不在上面的架构中.然而我将它们从FrontEnd发送到BackEnd作为req.parameter- 通常的事情,但我想肯定地说:)
MrG*_*iel -1
尝试这个:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
我希望它能帮助你