node.js - 为什么填充在 mongodb 中返回空结果
问题描述
我想填充我的属性(子类别),但它返回空,尽管我的数据库中有结果。我错过了什么吗?我按照猫鼬中的填充方法:
const Document = mongoose.model('Document', new mongoose.Schema({
name: { type: String },
description: { type: String },
subCategory: { type: mongoose.Schema.Types.ObjectId }
}));
const Category = mongoose.model('Category', new mongoose.Schema({
name: { type: String },
subCategories: [
{
name: { type: String }
}
]
})
);
var cat1 = await new Category({ name: 'cat1', subCategories: [{ name: 'sub-1-cat-1' }, { name: 'sub-1-cat-2' } ]}).save();
var cat2 = await new Category({ name: 'cat2', subCategories: [{ name: 'sub-2-cat-1' }, { name: 'sub-2-cat-2' } ]}).save();
await new Document({ name: 'doc1', description: 'blabla', subCategory: cat2.subCategories[1] }).save();
const results = Document.find({}).populate('subCategory');
// results[0].subCategory is empty?! why?
解决方案
子类别必须是猫鼬模型才能填充,目前您尝试填充的子类别只是类别模型的数组项,因此我会将您在上面发布的代码重构为:
const SubCategory = mongoose.model('SubCategory', new mongoose.Schema({
name: { type: String }
}));
const Document = mongoose.model('Document', new mongoose.Schema({
name: { type: String },
description: { type: String },
subCategory: { type: mongoose.Schema.Types.ObjectId, ref: "SubCategory" }
}));
const Category = mongoose.model('Category', new mongoose.Schema({
name: { type: String },
subCategories: [
{ type: mongoose.Schema.Types.ObjectId, ref: "SubCategory" }
]
})
);
var sub1Cat1 = await new SubCategory({ name: 'sub-1-cat-1' }).save();
var sub1Cat2 = await new SubCategory({ name: 'sub-1-cat-2' }).save();
var sub2Cat1 = await new SubCategory({ name: 'sub-2-cat-1' }).save();
var sub2Cat2 = await new SubCategory({ name: 'sub-2-cat-2' }).save();
var cat1 = await new Category({ name: 'cat1', subCategories: [sub1Cat1, sub1Cat2 ] }).save();
var cat2 = await new Category({ name: 'cat2', subCategories: [sub2Cat1, sub2Cat2 ] }).save();
await new Document({ name: 'doc1', description: 'blabla', subCategory: cat2.subCategories[1] }).save();
const results = Document.find({}).populate('subCategory');
// results[0].subCategory is not empty!
推荐阅读
- php - Webcrawler 提取链接元素
- javascript - 在 iE 的浏览器会话中手动添加 cookie
- html - IE11 中的 max-width 和 flex 不起作用
- ruby - 在不显示任何错误消息的情况下保存记录不起作用 - Rails
- angular - (Angular Universal) - firebase.initializeApp 不是函数
- php - 我怎样才能同时抓取两个不同的东西并将其存储在 MySQL 数据库中
- python - 条件映射模块导入
- firebase - 在 Cloud Firestore 事务中,如果我们不知道文档名称,如何检查文档是否存在于特定集合中
- android - 反应原生Android中不精确的高度和getItemLayout
- c++ - Can two stores be reordered in such singleton implementation?