2013-10-15 80 views
13

似乎有关于此主题stackoverflow上有很多Q/A的,但我似乎无法找到任何地方的确切答案。模型的Mongoose嵌套查询引用模型的字段

我有什么:

我有公司和个人型号:

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

我需要什么:

发现人们与姓氏 “罗伯逊” 已经成立的所有公司

我试过了:

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

然后我想,人是没有嵌入,但引用的,所以我用填入填充创办人称,然后试图用与“罗伯特森姓氏找到

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

回答

27

你不能在单个查询中这样做,因为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 
    }); 
}); 
+0

你说的没错,这看起来像一个关节。我给了你我想要实现的最简单的嵌套查询,这可能是关系数据库更方便的情况。但无论如何,你的解决方案工作。日Thnx! – AzaFromKaza

+0

你好,我正在寻找这个答案,因为我有同样的问题,但最后一个问题,有这个变化,或现在可以在猫鼬3.8.5?我意识到自从这个问题被张贴猫鼬上了几个版本。 – maumercado

+0

@maumercado不,它没有改变,不太可能。 – JohnnyHK

1

如果有人遇到这种在更近的时候,猫鼬现在支持加入像一个叫做填充功能组合。

从猫鼬文档:

Story. 
findOne({ title: 'Casino Royale' }). 
populate('author'). 
exec(function (err, story) { 
    if (err) return handleError(err); 
    console.log('The author is %s', story.author.name); 
    // prints "The author is Ian Fleming" 

});

http://mongoosejs.com/docs/populate.html