You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:35:26