How to output ‘id’ instead of ‘_id’ with MongoDB?

Sometimes, we want to output ‘id’ instead of ‘_id’ with MongoDB.

In this article, we’ll look at how to output ‘id’ instead of ‘_id’ with MongoDB.

How to output ‘id’ instead of ‘_id’ with MongoDB?

To output ‘id’ instead of ‘_id’ with MongoDB, we call schema’s virtual method to add a new computed field and return the _id value with the field.

And then we call set to set virtuals to true to return the field.

For instance, we write

Schema.virtual('id').get(function() {
  return this._id.toHexString();
});

Schema.set('toJSON', {
  virtuals: true
});

to call virtual with 'id' to create the id field.

And we call get with a function to return the hex string version of the _id with toHexString.

Finally, we call set with 'toJSON' and an object with virtuals set to true to return the id property with the result.

Conclusion

To output ‘id’ instead of ‘_id’ with MongoDB, we call schema’s virtual method to add a new computed field and return the _id value with the field.

And then we call set to set virtuals to true to return the field.