Mongoose nested query on Model by field of its referenced model

前端 未结 3 688
旧时难觅i
旧时难觅i 2020-11-29 02:22

It seems like there is a lot of Q/A\'s on this topic on stackoverflow, but I can\'t seem to find an exact answer anywhere.

What I have:

I

3条回答
  •  -上瘾入骨i
    2020-11-29 02:28

    You can't do this in a single query because MongoDB doesn't support joins. Instead, you have to break it into a couple steps:

    // Get the _ids of people with the last name of Robertson.
    Person.find({lastname: 'Robertson'}, {_id: 1}, function(err, docs) {
    
        // Map the docs into an array of just the _ids
        var ids = docs.map(function(doc) { return doc._id; });
    
        // Get the companies whose founders are in that set.
        Company.find({founder: {$in: ids}}, function(err, docs) {
            // docs contains your answer
        });
    });
    

提交回复
热议问题