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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With