복붙노트

[MONGODB] 참조 된 모델의 필드에 의해 모델에 중첩 된 쿼리를 몽구스

MONGODB

참조 된 모델의 필드에 의해 모델에 중첩 된 쿼리를 몽구스

유래에이 주제에 대한 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}};

내가 필요한 것:

성 "로버트슨"가진 사람들이 설립 한 것을 모든 기업을 찾기

내가 뭘하려합니다 :

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

그때 채우기 설립자 - 사람에 채우기를 사용하고 그럼 난 사람이 포함되지만 참조되지 않는다는 생각, 그래서 '로버트슨'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
    });

나는 아직도 String로서 사람의 ID로 회사를 조회 할 수 있습니다. 그러나 당신이 이해할 수 정확히 내가 원하는 아니다

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

해결법

  1. ==============================

    1.MongoDB를 조인을 지원하지 않기 때문에 단일 쿼리에서이 작업을 수행 할 수 없습니다. 대신, 당신은 몇 단계로 그것을 깰해야합니다 :

    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
        });
    });
    
  2. ==============================

    2.경우에는 사람이 더 최근에이 건너 온다, 몽구스는 이제 지원은 채우기라는 기능을 기능처럼 가입 할 수 있습니다.

    경우에는 사람이 더 최근에이 건너 온다, 몽구스는 이제 지원은 채우기라는 기능을 기능처럼 가입 할 수 있습니다.

    몽구스 문서에서 :

    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

  3. from https://stackoverflow.com/questions/19380738/mongoose-nested-query-on-model-by-field-of-its-referenced-model by cc-by-sa and MIT license