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