Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 369
Luka Avatar asked Mar 07 '12 12:03

Luka


People also ask

Can we change _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.

What is _ID in MongoDB?

What Is MongoDB ObjectID? As MongoDB documentation explains, "ObjectIds are small, likely unique, fast to generate, and ordered." The _id field is a 12-byte Field of BSON type made up of several 2-4 byte chains and is the unique identifier/naming convention MongoDB uses across all its content.

What is the default size for _ID field in MongoDB?

The default unique identifier generated as the primary key ( _id ) for a MongoDB document is an ObjectId. This is a 12 byte binary value which is often represented as a 24 character hex string, and one of the standard field types supported by the MongoDB BSON specification.

What is MongoDB projection?

Advertisements. In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.


1 Answers

Try this solution:

app.get('/itesms', function(req, res) {
  items.find({}, { _id: 0 }).toArray(function (err, array) {
    res.send(array);
  })
});
like image 56
Vadim Baryshev Avatar answered Oct 22 '22 10:10

Vadim Baryshev