如何使用mongoose将Multile 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);
当我尝试在DB中创建一个带有相关标签的新产品(来自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("/");
}
});
如何一次性将标签集合直接保存在产品中?是否更好地创建产品,然后使用推送逐个插入标签?
非常感谢你的帮助 !
回答如下:我认为这与Asynchrone JS有关,但我不确定。循环似乎不是一个好主意...
如何轻松地将多个标签文档保存到一个产品文档中?