【发布时间】:2020-10-19 18:55:23
【问题描述】:
我正在尝试将多个标签保存到我刚刚创建的特定产品中。我成功地将标签推送到产品集合中,但是当我尝试保存它时出现错误:无法同时保存()同一个文档多次。
我正在使用 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 中的代码(来自 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("/");
}
});
如何一次将标签集合直接保存在产品中?创建产品然后使用 push 将标签一一插入是否更好?
非常感谢您的帮助!
【问题讨论】: