2012-11-06 5 views
2

내가하려고하는 것은 내 .js 파일에 정의 된 articles 스키마에 액세스하는 자바 스크립트 함수를 작성하는 것입니다. 내 아래 시도 올바른 mongodb 쿼리를 자바 스크립트 함수

db.articles.ensureIndex({ "comments.user_id" : 1 }) 
     db.articles.find({ "comments.user_id" : 987654 }) // returns all document fields, meaning X and Y including comments 

     db.articles.find({ "comments.user_id" : 987654 }, 
{ "title" : 1, "comments.user_id" : 1 }) //some trimming 
자바 스크립트 함수의 목적은 특정 사용자의 모든 코멘트를 검색하는 것입니다

입니다

에 대응 :

난 이미 아래 쿼리는 MongoDB를 터미널에서 작동하는 것으로 확인 위의 mongodb 쿼리? 스타일, 구문이 우수 사례로 간주됩니까?

exports.allCommentsByUser = function(userId){ 
    db.articles.ensureIndex({"comments.user_id" : 1}) 
    var allComments = db.articles.find({"comments.user_id" : userId}, 
        { "title" : 1, "comments.user_id" : 1 }); 
    return allComments; 
} 

Q : 또한, 내가 어떻게이 폐쇄 기능에 자바 스크립트 함수 위의 변환합니까?

참고 : 내가 allComments는 몽구스 Query 목적이 아니라 결과이기 때문에 작동하지 않습니다 래퍼

답변

1

mongoose을 사용하고 있습니다. 비동기 find 호출이 완료되면 메소드가 호출자에게 결과를 제공하기 위해 사용할 콜백 매개 변수를 allCommentsByUser 메소드에 추가해야합니다. 방법의

exports.allCommentsByUser = function(userId, callback){ 
    db.articles.find(
     {"comments.user_id" : userId}, 
     { "title" : 1, "comments.user_id" : 1 }, 
     callback); 
}; 

사용법 :

x.allCommentsByUser(userId, function (err, articles) { 
    if (err) { 
     console.error(err); 
    } else { 
     console.log(articles); 
    } 
}); 

아니 당신이 '폐쇄 기능'에 대한 두 번째 질문에 요구하는지 확인합니다.

+0

'ensureIndex'를 포함하도록 함수를 업데이트했습니다. – bouncingHippo

+0

'ensureComponentByUser' 메소드에'ensureIndex' 호출을 넣고 싶지 않을 것입니다. 스키마 정의의 일부로 그렇게 할 수 있습니다. – JohnnyHK

+0

당신은'ensureIndex'를 스키마 정의의 일부로 두는 예를 보여줄 수 있습니까? – bouncingHippo