猫鼬在模型上按其引用模型的字段进行嵌套查询 [英] Mongoose nested query on Model by field of its referenced model

查看:83
本文介绍了猫鼬在模型上按其引用模型的字段进行嵌套查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于stackoverflow的这个主题似乎有很多问题,但是我似乎在任何地方都找不到确切的答案.

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.

我所拥有的:

我有Company和Person模型:

I have Company and Person models:

var mongoose = require('mongoose');
var PersonSchema = new mongoose.Schema{
                        name: String, 
                        lastname: String};

// company has a reference to Person
var CompanySchema = new mongoose.Schema{
                        name: String, 
                        founder: {type:Schema.ObjectId, ref:Person}};

我需要什么:

查找姓氏为"Robertson"的人创建的所有公司

Find all companies that people with lastname "Robertson" have founded

我尝试过的事情:

Company.find({'founder.id': 'Robertson'}, function(err, companies){
    console.log(companies); // getting an empty array
});

然后我发现Person不是嵌入式的,而是被引用的,所以我使用填充填充了Founder-Person,然后尝试使用带有'Robertson'姓氏的find

Then I figured that Person is not embedded but referenced, so I used populate to populate founder-Person and then tried to use find with 'Robertson' lastname

// 1. retrieve all companies
// 2. populate their founders
// 3. find 'Robertson' lastname in populated Companies
Company.find({}).populate('founder')
       .find({'founder.lastname': 'Robertson'})
       .exec(function(err, companies) {
        console.log(companies); // getting an empty array again
    });

我仍然可以用Person的id作为字符串查询公司.但这并不是您想要的完全是我想要的

I still can query companies with Person's id as a String. But it's not exactly what I want as you can understand

Company.find({'founder': '525cf76f919dc8010f00000d'}, function(err, companies){
    console.log(companies); // this works
});

推荐答案

您不能在单个查询中执行此操作,因为MongoDB不支持联接.相反,您必须将其分为几个步骤:

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
    });
});

这篇关于猫鼬在模型上按其引用模型的字段进行嵌套查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆