我有一个名为
categories
的 MongoDB 集合,它有一个自引用(parent
),如下所示。
const schema = mongoose.Schema({
name: String,
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
}
});
export default mongoose.model('Category', schema);
当我查询时,它只返回引用文档的对象 ID。
{
"_id": "63731fe1ce1bf2f534f9307e",
"name": "Glass cleaners",
"parent": "63731fbbce1bf2f534f9307d",
}
我想加载
parent
引用的文档,所以我使用以下代码单独加载父级。
let parentCat = await Category.findOne({ _id: category.parent });
有没有一种简单的方法可以做到这一点,因为在我看来,上面的内容有点难以维护。
谢谢
您可以在 mongoose 中使用查询population,而不是再次查询parent。
https://mongoosejs.com/docs/populate.html
当您查询将加载父文档时,您必须调用
populate()
。
Category.find().populate('parent');
强烈建议您阅读 mongoose 文档。