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
作爲包裝
我更新了函數以包含'ensureIndex' – bouncingHippo
您不希望將'ensureIndex'調用放在'allCommentsByUser'方法中。你會這樣做,作爲你的模式定義的一部分。 – JohnnyHK
你能告訴我一個將'ensureIndex'作爲模式定義一部分的例子嗎? – bouncingHippo