Mongoose返回数组$ 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){ });但似乎行不通。 有人可以帮帮我吗? :)
提前致谢。
I have a document :
{ _id: 98556a665626a95a655a, first_name: 'Panda', last_name: 'Panda, notifications: [{ _id: '', // ... }] }I want to return the following response :
{ _id: 98556a665626a95a655a, first_name: 'Panda', last_name: 'Panda', notifications: 2 }The problem is about notifications count field,
I used Mongoose NodeJS package and I tried the following :
UserDBModel.findOne({_id: uid}, {notifications: {$size: '$notifications'}}, function(err, user){ });But it seems to not work. Someone can help me ? :)
Thanks in advance.
最满意答案
将aggregate与project管道运算符一起使用。
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] });请注意,您必须明确指定项目操作员的字段。
Use aggregate with a project pipeline operator.
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] });Note that you will have to explicitly specify the fields for the project operator.
更多推荐
发布评论