2014-09-25 64 views
2

的长度这是我的猫鼬模式的一个例子:猫鼬得到的只是一个场

mongoose.model('Support', { 
    createdBy: mongoose.Schema.Types.ObjectId, 
    title: String, 
    replies: { type: Array, default: [] } 
} 

的答复数组可以包含几个对象,对此我不感兴趣的第一个查询,但我需要数组的长度。

这个问题有猫鼬解决方案吗?目前我只是循环浏览每个文档。

我迄今为止代码:

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 */ 
    } 
}); 

回答

1

您可以使用$size运营商aggregate让出数组中元素的个数:

Support.aggregate(
    {$project: { 
     createdBy: 1, 
     title: 1, 
     replies: {$size: '$replies'} 
    }}, 
    function(err, docs) { ... } 
);