我正在尝试将多个标签保存到我刚刚创建的特定产品。我成功地将标签推入到产品集合中,但是当我尝试保存它时,我得到了一个错误:无法并行多次保存()同一个文档。
我使用的是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);这里是我的node.js代码,当我试图在DB中创建一个带有相关标签的新产品时(来自一个HTML表单)
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("/");
}
});如何一次将标签集合直接保存到产品中?创建产品,然后使用推送逐个插入标签更好吗?
非常感谢你的帮助!
发布于 2020-10-19 18:50:04
问题可能是因为您试图通过执行以下操作来推送对象而不是_id
newitem.tags.push(finalcast);尝试像这样推送object的_id:
newitem.tags.push(finalcast._id);发布于 2019-04-05 17:16:19
我认为这与Asynchrone JS有关,但我不确定。循环似乎不是一个好主意……
如何轻松地将多个标签文档保存到一个产品文档中?
发布于 2019-04-06 01:30:50
好的,经过几个小时的工作,我找到了一个解决方案。我真的不知道这是不是一个好的方法,但它是有效的。我在forEach中插入一个if(),以便仅在forEach循环完成时保存:
req.body.tags.forEach(function(newtag, index){
tag.findOne({tagname : newtag},function(err, finalcast){
newitem.tags.push(finalcast);
if(index + 1 == req.body.tags.length){
newitem.save();
res.redirect("/");
}
});https://stackoverflow.com/questions/55524666
复制相似问题