lucaconlaq
lucaconlaq

Reputation: 1541

remove _id from mongo result

I'm pretty new with mongo and nodejs I've a json as result of my query and I simply want to return the result as an http request, as following:

app.get('/itesms', function(req, res) {
  items.find().toArray(function (err, array) {
    res.send(array);
  })
});

It works, only problem is that I want to hide the _id fields (recursively) from the result. Any suggestion to do that in an elegant way?

Upvotes: 23

Views: 34473

Answers (3)

Yishai Landau
Yishai Landau

Reputation: 630

The problem is that you can't project inclusions and exclusions, ie you can't run a query with a 'project' statement that declares what should be included in the response as well as what must be excluded from the response. From MongoDB documentation:

A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field. In projections that explicitly include fields, the _id field is the only field that you can explicitly exclude.

The way I handled this problem was to go to the end of the process, right before returning the response:

const dbObjectJSON = dbObject.toJson();
delete dbObjectJSON._id;
delete dbObjectJSON.__v;
...
response.json(dbObjectJSON);

Hope this helps.

Upvotes: 0

user993683
user993683

Reputation:

The usual .find({}, {_id:0}) approach wasn't working for me, so I went hunting and found in another SO answer that in version 3 of the Mongo API, you need to write it like this: .find({}, {projection:{_id:0}}). So, for example:

let docs = await db.collection("mycol").find({}, {projection:{_id:0}}).toArray();

It seems that (in the nodejs API, at least) you can also write it like this:

let docs = await db.collection("mycol").find({}).project({_id:0}).toArray();

Upvotes: 39

Vadim Baryshev
Vadim Baryshev

Reputation: 26199

Try this solution:

app.get('/itesms', function(req, res) {
  items.find({}, { _id: 0 }).toArray(function (err, array) {
    res.send(array);
  })
});

Upvotes: 41

Related Questions