簡體   English   中英

貓鼬返回數組$ size

[英]Mongoose return array $size

我有一個文件:

{
    _id: 98556a665626a95a655a,
    first_name: 'Panda',
    last_name: 'Panda,
    notifications: [{
        _id: '',
        // ...
    }]
}

我想返回以下響應:

{
   _id: 98556a665626a95a655a,
   first_name: 'Panda',
   last_name: 'Panda',
   notifications: 2
}

問題是關於通知計數字段,

我使用了Mongoose NodeJS軟件包,並嘗試了以下操作:

UserDBModel.findOne({_id: uid}, {notifications: {$size: '$notifications'}}, function(err, user){ });

但這似乎行不通。 有人可以幫助我嗎? :)

提前致謝。

也許,您可以在節點中執行類似的操作。

UserDBModel.findOne({ '_id': uid }, 'notifications', function (err, notifications) {
  if (err) return handleError(err);

 console.log(notifications.length);
})

由於無論如何您都在使用JS,也許可以利用它的強大功能! :)

aggregateproject管道運算符一起使用。

UserDBModel.aggregate()
    .match({_id: uid})
    .project({
        first_name: 1,
        last_name: 1,
        notifications: {$size:"$notifications"}
    })
    .exec(function(err, notifications) {
        // notifications will be an array, you probably want notifications[0]
    });

請注意,您將必須為項目操作員明確指定字段。

我發現對我有用的是創建貓鼬虛擬屬性。

Schema.virtual('notifications_count').get(function() {
  if (this.notifications) {
    return this.notifications.length;
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM