首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在MongoDB中用mongoose将多个引用保存到一个文档中?

如何在MongoDB中用mongoose将多个引用保存到一个文档中?
EN

Stack Overflow用户
提问于 2019-04-05 04:49:05
回答 4查看 269关注 0票数 0

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

我使用的是mongoDB、node和Mongoose。

以下是我的模式

代码语言:javascript
复制
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);

这里是我的node.js代码,当我试图在DB中创建一个带有相关标签的新产品时(来自一个HTML表单)

代码语言:javascript
复制
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("/");

            }

        });

如何一次将标签集合直接保存到产品中?创建产品,然后使用推送逐个插入标签更好吗?

非常感谢你的帮助!

EN

Stack Overflow用户

发布于 2020-10-19 18:50:04

问题可能是因为您试图通过执行以下操作来推送对象而不是_id

代码语言:javascript
复制
newitem.tags.push(finalcast);

尝试像这样推送object的_id:

代码语言:javascript
复制
newitem.tags.push(finalcast._id);
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55524666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档