如何将对象添加到 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:在路径“products”处,对于值“[object Object]”,转换为未定义失败
最佳答案
由于 Partner
模型中的 products 字段是一个数组,其中包含对 Product
模型的 _id
引用,因此您应该推送一个 _id
到数组,而不是对象,因此 Mongoose 提示错误。
您应该重构代码以允许将 Product
_id 引用保存到 Partner
模型:
router.post('/addProduct', function (req, res) {
var product = new campSchema.Product(req.body.dataProduct);
product.save(function (err) {
if (err) return throw err;
campSchema.Partner.findByIdAndUpdate(
req.body.partnerId,
{ "$push": { "products": product._id } },
{ "new": true },
function (err, partner) {
if (err) throw err;
res.json(partner);
}
);
});
});
关于javascript - 如何使用 Node.js 和 Mongoose 将对象添加到嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37963226/