2015-12-21 82 views
2

我有一个文件:

{ 
    _id: 98556a665626a95a655a, 
    first_name: 'Panda', 
    last_name: 'Panda, 
    notifications: [{ 
     _id: '', 
     // ... 
    }] 
} 

我想返回如下回应:

{ 
    _id: 98556a665626a95a655a, 
    first_name: 'Panda', 
    last_name: 'Panda', 
    notifications: 2 
} 

的问题是有关通知计数字段,

我用猫鼬NodeJS软件包,我试过以下内容:

UserDBModel.findOne({_id: uid}, {notifications: {$size: '$notifications'}}, function(err, user){ }); 

但它似乎不起作用。 有人可以帮助我吗? :)

在此先感谢。

+0

该查询返回给您什么? – CodePhobia

+1

$ size操作符只会返回与您使用时指定的大小相匹配的字段(它需要一个数字)。如果你想要它*返回数组中的项目数*然后你必须在**聚合**中使用它。这里是[链接](https://docs.mongodb.org/v3.0/reference/operator/aggregation/size/)。如果不是,请尝试使用数组的.length属性,如答案中所示。 – jmugz3

回答

2

使用aggregateproject管道运营商。

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] 
    }); 

请注意,您将不得不明确指定项目操作员的字段。

+0

谢谢它的作品!只需要添加mongoose.Types.ObjectId(uid)而不是uid。 –

2

也许,你可以在你的节点上做这样的事情。

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

console.log(notifications.length); 
}) 

由于您使用JS反正可能会使用它的力量! :)

+0

是的,但我想避免使用内存与通知数组内容时,我只需要对它们进行计数。 –

+0

好的!如果你期望通知数组很庞大,那么这就是要走的路,Mongo会为你付出沉重的代价。但是请注意,在mongodb的集合中有无限增长的数组是一个糟糕的设计。 :) – CodePhobia