【发布时间】:2016-10-24 02:41:00
【问题描述】:
如何将对象添加到PartnerSchema 中的嵌套数组?
我将文档分开,因为将来会有更多的嵌套数组。
这是我的架构:
var productSchema = new mongoose.Schema({
name: String
});
var partnerSchema = new mongoose.Schema({
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}]
});
module.exports = {
Partner: mongoose.model('Partner', partnerSchema),
Product: mongoose.model('Product', productSchema)
}
这是我的后端:
var campSchema = require('../model/camp-schema');
router.post('/addPartner', function (req, res) {
new campSchema.Partner({ name : req.body.name }).save(function (err, response) {
if (err) console.log(err);
res.json(response);
});
});
router.post('/addProduct', function (req, res) {
campSchema.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);
});
});
我可以使用/addPartner添加合作伙伴,它工作正常。
问题在于第二个函数/addProduct 我无法将产品添加到合作伙伴架构中的数组。我有一个错误:CastError: Cast to undefinded failed for value "[object Object]" at path "products"
【问题讨论】:
标签: javascript arrays node.js mongodb mongoose