【问题标题】:Remove _Id from mongoose Aggregate response从 mongoose 聚合响应中删除 _Id
【发布时间】:2015-02-27 19:15:04
【问题描述】:

我正在尝试从返回的文档中删除 _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),但这只是剥离了超级对象('联系人')。

欢迎提出任何建议。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案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 () {
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2023-03-06
      • 1970-01-01
      • 2015-04-24
      • 2019-02-02
      相关资源
      最近更新 更多