Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: output 'id' instead of '_id'

I am using mongoose (node), what is the best way to output id instead of _id?

like image 269
Johnny Avatar asked Aug 12 '11 01:08

Johnny


People also ask

Can MongoDB _id be string?

Yes, you can. BTW, uniqueness guaranteed by mongodb. Because _id field has a unique index by default.

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.

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.

Can we rename _id in MongoDB?

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


1 Answers

Given you're using Mongoose, you can use 'virtuals', which are essentially fake fields that Mongoose creates. They're not stored in the DB, they just get populated at run time:

// Duplicate the ID field. Schema.virtual('id').get(function(){     return this._id.toHexString(); });  // Ensure virtual fields are serialised. Schema.set('toJSON', {     virtuals: true }); 

Any time toJSON is called on the Model you create from this Schema, it will include an 'id' field that matches the _id field Mongo generates. Likewise you can set the behaviour for toObject in the same way.

See:

  • http://mongoosejs.com/docs/api.html
  • http://mongoosejs.com/docs/guide.html#toJSON
  • http://mongoosejs.com/docs/guide.html#toObject

You can abstract this into a BaseSchema all your models then extend/invoke to keep the logic in one place. I wrote the above while creating an Ember/Node/Mongoose app, since Ember really prefers to have an 'id' field to work with.

like image 61
Pascal Zajac Avatar answered Sep 20 '22 23:09

Pascal Zajac