【问题标题】:How to add object to nested Array using Node.js and Mongoose如何使用 Node.js 和 Mongoose 将对象添加到嵌套数组
【发布时间】: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


    【解决方案1】:

    由于 Partner 模型中的 products 字段是一个数组,其中包含 _idProduct 模型的引用,因此您应该将 _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);
                }
            );
        });
    });
    

    【讨论】:

    • 名字呢?此代码仅添加具有 id 的产品。我还必须将req.body.dataProduct.name 添加到产品中的名称字段
    • 无需添加名称,因为 Mongoose 会在您进行填充时自动为您添加名称。您需要了解猫鼬种群的概念,建议您阅读更多here
    • { "_id" : ObjectId("576a4ed4318781680dc3e57f"), "name" : "examplePartner", "products" : [ ObjectId("576a5e54e8b3585818502fc4") ], "__v" : 0 } 正如您在 products 数组中看到的,只有 ID。没有名字...
    • 应该是这样,只是一个带有_ids 的数组。如果您正确理解 Mongoose 填充的功能,那么您将知道当您查询集合时它会在幕后自动为您创建文档。在上面的实例中,您正在保存数据,因此无需将其保存为对象,因为您已在架构中定义它以使用 ref 属性。我鼓励您阅读有关主题populate 的更多内容,以便更好地理解。
    • 好的,我明白了。现在我想知道分开文件是否是个好主意。因为我将如何向特定的合作伙伴展示产品。之前我在合作伙伴内部拥有产品时,这很容易 - li(ng-repeat="product in partner.products") a(href="#") {{ product.name }} 所以也许我不应该将这些文件分开?
    猜你喜欢
    • 2019-04-23
    • 2021-08-13
    • 1970-01-01
    • 2017-08-29
    • 2021-09-01
    • 2020-12-20
    • 1970-01-01
    • 2016-06-19
    • 2019-02-13
    相关资源
    最近更新 更多