node.js - 如何使用 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 将标签一一插入是否更好?
非常感谢你的帮助 !
解决方案
问题可能是因为您尝试通过执行来推送对象而不是 _id
newitem.tags.push(finalcast);
尝试像这样推送对象的 _id:
newitem.tags.push(finalcast._id);
推荐阅读
- json - 语法错误,意外的keyword_end,需要')'
- php - 记录到数据库 BLOB 列长时间运行的 php 脚本的内存有效方式
- google-analytics - 如何在 Google Analytics 中分析多个查询参数
- angular - 角度 github 构建并非所有图像都获取应用程序 URL(和其他内容)
- javascript - 在网页上显示 Discord 服务器成员数?
- python - matplotlib.pyplot.savefig 需要很长时间
- bash - Bash:在单行(作为参数)上获得带空格的文件名的打乱列表?
- css - 静态django链接css文件
- javascript - 检查预定义角色并执行命令
- javascript - Javascript - 在 promise 和 await 之间不保存本地对象变量