模型的Mongoose嵌套查询引用模型的字段

这似乎有很多Q / A在这个话题在stackoverflow,但我似乎无法find一个确切的答案在任何地方。

我拥有的:

我有公司和个人模型:

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

我需要的:

find所有拥有“罗伯逊”姓氏的公司成立的公司

我试过的:

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

然后我觉得Person并不是embedded式的,而是被引用的,所以我使用populate填充了创build者Person,然后试图用'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's id的公司作为string。 但是,这不完全是我想要的,因为你可以理解

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