Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose return array $size

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.

like image 361
Nïrio Avatar asked Oct 24 '25 17:10

Nïrio


1 Answers

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.

like image 116
weiyin Avatar answered Oct 26 '25 05:10

weiyin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!