如何在Mongoose中加载引用文档?



我有一个叫做categories的MongoDB集合,它有一个自我引用(parent),如下所示。

const schema = mongoose.Schema({
name: String,
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
}
});
export default mongoose.model('Category', schema);
When i query it just returns the object id of the referenced document.

{"_id"63731 fe1ce1bf2f534f9307e"名称";玻璃清洁剂";"parent"63731 fbbce1bf2f534f9307d"}


I want to load the document referenced by `parent`, so i used following code to load the parent seperatly.

let parentCat = await Category。findOne({_id:类别。父母});


Is there an easy way of doing this because above is bit difficult to maintain if in my opinion.
Thanks

您可以在mongoose中使用查询population而不是再次查询parent。

https://mongoosejs.com/docs/populate.html

你必须调用populate()当你查询将加载父文档。

Category.find().populate('parent');

强烈建议您阅读mongoose文档。

最新更新