node.js - Mongoose 通过其引用模型的字段对模型进行嵌套查询

标签 node.js mongodb mongoose populate

stackoverflow 上似乎有很多关于此主题的 Q/A,但我似乎无法在任何地方找到确切的答案。

我有什么:

我有公司和个人模型:

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”的人创建的所有公司

我尝试了什么:

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

然后我发现 Person 不是嵌入的而是引用的,所以我使用 populate 来填充创始人-Person,然后尝试使用带有 'Robertson' lastname 的 find

// 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 作为字符串来查询公司。但这并不是我想要的,正如你所理解的那样

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

最佳答案

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

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

关于node.js - Mongoose 通过其引用模型的字段对模型进行嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19380738/

相关文章:

javascript - 在 node.js 中用一个模块替换另一个模块

javascript - 获取一个数组中的所有数组元素 mongodb + node.js

typescript - TypeScript 中的 Mongoose 自定义查询助手

node.js - 使用 .toArray 查询不会返回任何结果供查看

javascript - 将 json 转换为 xml 并删除空字符串

javascript - 从 mongodb 回调将值设置为外部变量

MongoDB - "The dollar ($) prefixed field\' $$hashKey\' in\' 字段名".$$hashKey\' is not valid for storage.' "

c# - 使用 MongoDB C# 驱动程序将项目添加到嵌套对象的嵌套数组

node.js - Mongoose :.find() 不是函数

mysql - 向 Node 表达mysql同步问题的多个请求