【问题标题】:How many database queries executing when using populate?使用填充时执行了多少个数据库查询?
【发布时间】:2019-07-22 01:22:20
【问题描述】:

有以下场景 -

   const Person = mongoose.model('Person', {
        name: String
    });
    const FamilyTree = mongoose.model('FamilyTree', {
        person: { type: Schema.Types.ObjectId, ref: 'Person' },
        children: [FamilyTree]
    });


    const run = async => {
        await Promise.all(['Bob', 'Mike', 'Rory'].map( name => Person.create({name}) ));

        let bob = await Person.find({name: 'Bob'}); // [request to BD] total requests = 1
        let mike = await Person.find({name: 'Mike'}); // [request to BD] total requests = 2
        let rory = await Person.find({name: 'Rory'}); // [request to BD] total requests = 3

        await FamilyTree.create({
            person: bob._id,
            children: [
                {
                    person: mike._id,
                    children: [
                        {
                            person: rory._id,
                            children: []
                        }
                    ]
                }
            ]
        });

        await FamilyTree.find().populate('person').exec(); // how many db requests will there be? 1 or 3?
    }

如果响应包含以下数据,则使用填充时执行多少个数据库查询?

从数据库中提取的数据 -

{
    person: {name: 'Bob'},
    children: [{person: 'Mike', children: [{name: 'Rory', children: []}]}]
}

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    很好的问题,我也很好奇。然后我找到了这个。

    Mongoose 在幕后做了一些聪明的事情。如果您查看作为此填充查询的结果而进行的实际查询,它会在引擎盖下看起来像这样

    FamilyTree.find({});
    person.find({ _id: { $in: ['5678', '9012', '3456'] } });
    

    所以它只是一个$in 查询! Mongoose 收集每个集合需要查找的所有 _id 字段,然后……我不太确定。查看源代码,它似乎做了一些聪明的事情来反映该查询的结果并将正确的对象映射回每个原始文档,基于它在您传递给查询的填充图中的位置......或其他东西像这样(如果你愿意的话,你可以查看从 lib/model.js 的 2468 行开始的源代码)。

    参考:http://frontendcollisionblog.com/mongodb/2016/01/24/mongoose-populate.html

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 2021-07-28
      • 1970-01-01
      相关资源
      最近更新 更多