mongoose只得到一个字段的长度
这是我的Mongoose模式的一个例子:
mongoose.model('Support', { createdBy: mongoose.Schema.Types.ObjectId, title: String, replies: { type: Array, default: [] } }
回复数组可以包含几个对象,我对第一个查询不感兴趣,但是我确实需要数组的长度。
是否有mongoose解决这个问题? 目前我只是循环每个文件。
我的代码到目前为止:
Support.find({}, function(err, docs) { if (err) throw err; async.each(docs, function(doc, next) { doc.replies = doc.replies.length; next(); }, function() { /* Work with the result */ } });
您可以使用具有aggregate
的$size
运算符来获取数组中的项目数量:
Support.aggregate( {$project: { createdBy: 1, title: 1, replies: {$size: '$replies'} }}, function(err, docs) { ... } );