我需要计算主文档的子文档。只是一个方案的例子:
型号:
{
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); }
});
如何计算某些文档中的评论?
答案 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);
};