首页 > 解决方案 > 如何使用 mongoose 将多个 refs 保存到 MongoDB 中的一个文档中?

问题描述

我正在尝试将多个标签保存到我刚刚创建的特定产品中。我成功地将标签推送到产品集合中,但是当我尝试保存它时出现错误:无法同时保存()同一个文档多次。

我正在使用 mongoDB、node 和 Mongoose。

这是我的架构


var tagSchema = mongoose.Schema({
    tagname: String,
});

var tag = mongoose.model('Tag', tagSchema);


var Item = new Schema({
    title : String,
    description : String,
    price : Number,
    tags:  [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Tag"
    }]
});

var product = mongoose.model('Product', Item);

当我尝试在数据库中创建具有关联标签的新产品时(来自 HTML 表单),这里是我在 node.js 中的代码


product.create(req.body.product, function(err, newitem){
            if(err){
                console.log(err);
            }else{

             console.log(req.body.tags); // gives ["fun","cheap"] from the form
             req.body.tags.forEach(function(newtag){
             tag.findOne({tagname : newtag},function(err, finalcast){


             newitem.tags.push(finalcast); 
             console.log(newitem); // gives the product with the tag collections in it.

               });
              newitem.save(); // error Can't save() the same doc multiple times in parallel.
              console.log(newitem); // the product collection has an empty tags[] 

               });


                 res.redirect("/");

            }

        });


如何一次将标签集合直接保存在产品中?创建产品然后使用 push 将标签一一插入是否更好?

非常感谢你的帮助 !

标签: node.jsmongodbmongoose

解决方案


问题可能是因为您尝试通过执行来推送对象而不是 _id

newitem.tags.push(finalcast);

尝试像这样推送对象的 _id:

newitem.tags.push(finalcast._id);

推荐阅读