23

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?

lucaconlaq
  • 1,511
  • 4
  • 19
  • 36

3 Answers3

38

Try this solution:

app.get('/itesms', function(req, res) {
  items.find({}, { _id: 0 }).toArray(function (err, array) {
    res.send(array);
  })
});
Vadim Baryshev
  • 25,689
  • 4
  • 56
  • 48
36

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();
  • 4
    This is the correct answer now. Did this as a guess after logging the value of docs without the await and it showed up as a Promise. Wasn't made very clear in their docs. – Aidan Jul 28 '19 at 17:37
  • This is what I needed. – anotherOne Jun 05 '21 at 21:17
  • If you're having trouble reading [the docs for how to suppress the `_id` field](https://www.mongodb.com/docs/v4.4/tutorial/project-fields-from-query-results/#suppress-_id-field), always make sure you go to the top-right corner of the web page and **select the language you are working with**. MongoDB Shell syntax is indeed `.find({}, { _id: 0 })` but Node.js driver syntax is `.find({}, { projection: { _id: 0 } })`. – Wyck Nov 10 '22 at 16:59
0

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.

Yishai Landau
  • 620
  • 4
  • 14