Mongoose返回数组$ size(Mongoose return array $size)

系统教程 行业动态 更新时间:2024-06-14 16:59:46
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.

更多推荐

本文发布于:2023-04-17 08:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/b419617e8a9300951818d8050ff6e2f6.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Mongoose   size   array   return

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!