Yossi
Yossi

Reputation: 341

Remove _Id from mongoose Aggregate response

I'm trying to remove the _Id from the returned documents, this is my code:

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

the current result-set looks like this:

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

I tried to replace "_Id" with "$project", or $project, and adding "_Id": 0 to the object, as some have suggested elsewhere, but was not successful.

I also tried res.send(contacts), but that only stripped the super-object ('contacts').

Any suggestions are appreciated.

Upvotes: 1

Views: 2043

Answers (2)

Łukasz
Łukasz

Reputation: 55

Bunch of time but, here is the answer:

After making $group or $project, do this:

{ $unset: ["_id"] }

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

Like this

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 () {

});

Upvotes: 3

Related Questions