是否可以在mongoose中获取从find()查询返回的文档数量

时间:2015-08-23 23:12:37

标签: node.js mongodb mongoose

我正在尝试使用mongoose中的find()查询来获取从数据库中获取的数据的数量。现在任何人都可以告诉我,我可以做下面的事情,还是我必须写其他功能来做到这一点

merchantmodel.find({merchant_id: merchant_id, rating: {'$ne': -1 }, review: {'$ne': "" }}, {'review':1, '_id':0}, {sort: {time_at: -1}}, function(err, docs) {
        if (err) {

        } else {
            if (docs) {
                console.log(docs[1].review);
                console.log(docs.size()); // Here by writing something is it possible to get count or not
                res.json({success: 1, message : "Successfully Fetched the Reviews"});
            }
        }
    });

2 个答案:

答案 0 :(得分:2)

将返回值转换为数组,然后使用length属性

var query = { merchant_id : merchant_id, rating : { '$ne': -1 }, review: { '$ne': "" }}; 
var projection = { 'review':1, '_id':0 }; 
var options = { sort: { time_at: -1 } };
merchantmodel.find(query, projection, options).toArray(function(err, docs) {
    if (err) {
        throw(err);
    }
    console.log(docs[1].review);
    console.log(docs.length);
    res.json({success: 1, message : "Successfully Fetched the Reviews"});
});

答案 1 :(得分:1)

你可以这样做:

console.log(docs.length);

docs方法返回的find()变量是一个数组,因此 docs.length 可以完成这项工作。

执行此操作的mongodb native way将是:

db.collection.find( { a: 5, b: 5 } ).count()
相关问题