2014-09-25 62 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) { ... } 
);