最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose return array $size - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Dec 21, 2015 at 16:53 NïrioNïrio 431 silver badge4 bronze badges 2
  • what did that query return to you? – CodePhobia Commented Dec 21, 2015 at 17:01
  • 1 the $size operator will only return the fields that matches the size specified when used like you used it (It expects a number). If you want it to return the number of items in the array then you must you use it in an aggregration. Here's the link. If not, try using the .length property of an array like suggested in the answers. – mugabits Commented Dec 21, 2015 at 17:17
Add a ment  | 

3 Answers 3

Reset to default 4

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.

Maybe, you could do something like this in your node.

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

 console.log(notifications.length);
})

Since you are using JS anyways maybe use its power! :)

What I found to work for me is creating a mongoose virtual attribute.

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

评论列表(0)

  1. 暂无评论