2012-11-06 48 views
2

我想要做的是寫一個javascript函數來訪問我的.js文件中定義的articles模式。mongodb查詢到javascript函數

我已經確定了以下查詢在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 

JavaScript函數的目的是爲了獲取特定用戶提出的所有意見,是我下面嘗試正確對應以上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; 
} 

問:此外,如何轉換JavaScript函數以上的閉合功能?

注:我使用mongoose作爲包裝

回答

1

這是行不通的,因爲allComments是貓鼬Query對象,而不是結果。您需要爲您的allCommentsByUser方法添加回調參數,該方法將在異步find調用完成後用於將結果返回給調用方。

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

您不希望將'ensureIndex'調用放在'allCommentsByUser'方法中。你會這樣做,作爲你的模式定義的一部分。 – JohnnyHK

+0

你能告訴我一個將'ensureIndex'作爲模式定義一部分的例子嗎? – bouncingHippo