2015-01-08 5 views
0

나는 사용자 게시물을 얻는 쿼리가 있고 나는 방문자가 선택한 국가의 게시물 만 표시하고 싶습니다.후 몽구스 사용 후 인구 :

은 지금까지 나는 이런 식으로 뭔가를 할 노력하고있어 :

var country = req.query.country || req.session.country || { $ne: '' }; 
    Posts.find({}) 
     .populate('_creator') 
     .where('_creator.country').equals(country) 
     .exec(function(err, posts) { 
      console.log(posts); 
    }); 

불행하게도 그것이 작동하지 않습니다.

어떻게 이와 비슷한 쿼리를 사용할 수 있습니까?

편집 :

이있는 게시물 스키마 : 초기 쿼리가 완료된 후 populate는 별도의 쿼리로 실행되기 때문에 당신은 당신의 쿼리에 채워진 필드를 포함 할 수 없습니다

var postsSchema = new mongoose.Schema({ 
    _creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, 
    text: { type: String, default: '' }, 
    created_at: Date 
}); 
+0

OK, 내가 게시 한 답변을 참조하십시오. 나는 그것이 중복 된 것처럼 여전히 질문을 마감했다. – JohnnyHK

+0

예, 멋지게 작동했습니다. 감사. –

답변

7

.

이 유형의 쿼리를 효율적으로 수행하는 한 가지 방법은 먼저 선택한 국가의 사용자 ID를 조회 한 다음 해당 사용자의 게시물을 쿼리하는 것입니다.

// Get the _ids of the users of the selected country. 
User.find({country: country}, {_id: 1}, function(err, users) { 

    // Map the user docs into an array of just the _ids 
    var ids = users.map(function(user) { return user._id; }); 

    // Get the posts whose _creator is in that set of ids 
    Post.find({_creator: {$in: ids}}).populate('_creator').exec(function(err, posts) { 
     // posts contains your answer 
    }); 
}); 
+0

예, 답은'_creator'의 최종 채우기가 부족합니다. 그렇습니다. 정확하고 문제를 해결했습니다. 당신의 도움을 주셔서 감사합니다. 건배. –

+0

@AyeyeBrazo 좋은 지적 - 추가됨. – JohnnyHK