2012-11-06 42 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