从mongoose Aggregate响应中删除_Id

时间:2014-12-31 19:24:13

标签: node.js mongodb express mongoose

我正在尝试从返回的文档中删除_Id,这是我的代码:

module.exports = function(app) {
    // Module dependencies.
    var mongoose = require('mongoose'),
        Contacts = mongoose.models.Contacts,
        api = {},
        limit = 10;

    api.contacts = function(req, res) {

        Contacts.aggregate([{
                $group: {
                    "_id": {
                        name: "$name",
                        city: "$city",
                        state: "$state"
                    }
                }
            }, {
                $sort: {
                    AgencyTranslation: 1
                }
            }, {
                $limit: req.query.limit | limit
            }],
            function(err, contacts) {
                if (err) {
                    res.json(500, err);
                } else {
                    res.json({
                        contacts: contacts
                    })
                }
            })
    };

    app.get('/api/contacts', api.contacts);
};

当前的结果集如下所示:

{
   "contacts":[
       {"_id":{"name":"Joe","city":"ankorage","state":"AL"}},
       {"_id":{"name":"Mark","city":"washington","state":"DC"}}
       ...
   ]
}

我尝试将“_Id”替换为“$ project”或$ project,并将“_Id”:0添加到对象中,正如有些人在别处建议的那样,但是没有成功。

我也尝试了res.send(contacts),但这只剥离了超级对象('contacts')。

任何建议都表示赞赏。

1 个答案:

答案 0 :(得分:1)

喜欢这个

Contacts.aggregate( [
    { $group: { "_id": { name: "$name",  city: "$city", state: "$state" } } },
    { $project: {_id: 0, name: '$_id.name', city: '$_id.city', state: '$_id.state'} },
    { $sort: { AgencyTranslation: 1 } },
    { $limit: req.query.limit | limit }
], function () {

});
相关问题