admin管理员组文章数量:1303068
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
3 Answers
Reset to default 4Use 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;
}
});
本文标签: javascriptMongoose return array sizeStack Overflow
版权声明:本文标题:javascript - Mongoose return array $size - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741728659a2394742.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论