2013-10-15 77 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