I need to count subdocuments of the main document. Just an example of scheme:
Model:
{
title: {type: String, required: true},
content: {type: String, required: true},
comments: [{
comment: {type: String, required: true},
author: {type: String, required: true}
}]
}
This query doesn't work:
Model.findById(ObjectId).count('comments', function(err, res) {
if (err) { throw err; }
else { console.log(res); }
});
How can I count comments in some document?
You can do this with .length
Model.findById(ObjectId, function(err, res) {
if (err) { throw err; }
if (!res) { console.log('model not found'); }
console.log(res.comments.length);
};