2013-10-15 19 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を文字列として持つ企業あなたはMongoDBのジョインをサポートしていないので、あなたは、単一のクエリでこれを行うことはできません

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

答えて

27

を理解することができるようしかし、それは私が欲しいものを正確ではありません。代わりに、あなたはカップルのステップにそれを破ることがあります。誰もが、より最近ではこの遭遇場合

// 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

あなたは正しく、ジョイントのように見えます。私は実装するために考えている最も単純なネストされたクエリを提供しました。おそらく、リレーショナルDBがより便利なケースです。しかし、とにかく、あなたのソリューションはうまくいった。 Thnx! – AzaFromKaza

+0

こんにちは、私は同じ問題があるので、私はこの答えを探していましたが、最後の質問が1つありました。これは変更されていますか、今ではmongoose 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