Mongoose - Count子文档

时间:2013-05-03 11:49:31

标签: node.js mongoose

我需要计算主文档的子文档。只是一个方案的例子:

型号:

{
    title: {type: String, required: true},
    content: {type: String, required: true},
    comments: [{
        comment: {type: String, required: true},
        author: {type: String, required: true}
    }]
}

此查询无效:

Model.findById(ObjectId).count('comments', function(err, res) { 
    if (err) { throw err; } 
    else { console.log(res); } 
});

如何计算某些文档中的评论?

1 个答案:

答案 0 :(得分:2)

您可以使用.length

执行此操作
Model.findById(ObjectId, function(err, res) {
    if (err) { throw err; }
    if (!res) { console.log('model not found'); }
    console.log(res.comments.length);
};