如何在Mongoose中自动加载自引用的parent关联文档?
解决Mongoose自引用集合加载关联文档的简便方法
方法1:使用populate()直接加载关联文档
Mongoose内置的populate()方法可以在查询时直接加载ref指定的关联文档,无需单独发起查询。
查询单个文档时:
const category = await Category.findById("63731fe1ce1bf2f534f9307e").populate('parent');
返回结果会自动将parent字段替换为完整的关联文档:
{ "_id": "63731fe1ce1bf2f534f9307e", "name": "Glass cleaners", "parent": { "_id": "63731fbbce1bf2f534f9307d", "name": "Cleaning supplies", "parent": null // 若父级无上级则为null,有上级可继续嵌套加载 } }
查询多个文档并加载父级:
const categories = await Category.find().populate('parent');
方法2:嵌套加载多级父文档
如果需要加载多层父级(比如父级的父级),可以使用嵌套populate语法:
const category = await Category.findById("63731fe1ce1bf2f534f9307e") .populate({ path: 'parent', populate: { path: 'parent' } // 加载父级的父级文档 });
方法3:设置默认自动加载(可选)
如果每次查询都需要加载parent,可以在Schema定义时配置前置钩子,避免重复编写populate():
const schema = mongoose.Schema({ name: String, parent: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', } }); // 配置find和findOne查询时自动populate parent schema.pre('find', function() { this.populate('parent'); }); schema.pre('findOne', function() { this.populate('parent'); }); export default mongoose.model('Category', schema);
之后直接调用find()或findOne(),会自动加载parent关联文档。
内容的提问来源于stack exchange,提问作者Pol Santha
相关产品推荐
相关产品推荐

