javascript - 如何使用 Node.js 和 Mongoose 将对象添加到嵌套数组

标签 javascript arrays node.js mongodb mongoose

如何将对象添加到 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/

相关文章:

javascript - 循环 3 次后停止动画

node.js - PM2 在集群模式下抛出 --harmony-async-await 的错误选项错误

javascript - 这个正则表达式与我认为应该匹配的东西不匹配

javascript - 在 textarea 字段中保留回车符(十六进制 0D)

C++ 赋值,strcpy 和 strlen 与字符数组 n 指针

java - 如何从 Angular 2 应用程序执行驻留在服务器上的 Java 代码?

node.js - 创建要在 bash 中使用的 Node Js 命令行缓冲区

javascript - Laravel @include 通过 ajax 的 Blade View

javascript - jQuery 中的多个 AJAX 请求

arrays - **在C语言中是做什么的?