node.js - 如何使用 mongoose refs 存储参考数据?
问题描述
我正在制作一个笔记应用程序,每个笔记都有多个类别。
var NotesSchema = new mongoose.Schema({
title: String,
note: String,
favorite: {type: Boolean, default: false},
category: [{ type: mongoose.Schema.Types.ObjectId, ref: "categories" }]
},{ timestamps: { createdAt: 'created_at' } });
var Notes = mongoose.model('Notes', NotesSchema);
var CategoriesSchema = new Schema({
name: {type: String, required: true},
favorite: {type: Boolean, default: false},
})
var Categories = mongoose.model('Categories', CategoriesSchema);
我只能对一个类别执行此操作,但我不知道如何对多个类别执行此操作。
首先,我认为我需要存储类别,获取每个 ID,然后存储注释。这是我尝试过的:
.get('/', (req, res) => {
var data = {
title : "scientific revolution",
note : " some note",
favorite : true,
category : [ 'science', 'books']
}
var catIds = [], seriesIds = [];
data.category.map(cat =>{
const category = new Categories({
name: cat
})
category.save((err,data)=>{
if(err) throw err;
catIds.push(data._id)
})
})
data.category = catIds;
const note = new Notes(data)
note.save((err, data)=>{
if(err) throw err;
res.json(data)
})
})
数组catIds
永远不会得到 id!
我对使用参考完全陌生。甚至不知道它们的存在。
解决方案
Your ref
field should point to the model name not the table name.
In this case Categories
.
I see you have write {ref: 'categories'}
with small c
but mongoose collection name is case sensitive and you should do {ref: 'Categories'}
.
You can read more about mongoose case sensitivity in this post
推荐阅读
- python - 使用多个 except 语句在 try/except 块之外返回错误
- ios - 重新加载数据时集合视图变为零
- r - 如何增加两个居中操作按钮之间的空间?
- javascript - plotly.js 的集成测试
- python - 如何使用索引对数据框中的值进行排名?
- javascript - document.getElementsByClassName 返回未定义
- ios - iOS MobileVLCKit 存档问题
- node.js - 如何修改 Joi 对象中的现有键
- android - 当我使用 arm64-v8a 设备下载 App Bundle 时,如何强制 Play 商店仅提供 armeabi-v7a APK?
- bash - HDFS 文件以千兆字节排序