What is the difference between id and _id in mongoose?

Javascriptnode.jsMongodbMongooseDatabase

Javascript Problem Overview


What is the difference between _id and id in mongoose? Which is better for referencing?

Javascript Solutions


Solution 1 - Javascript

From the documentation:

> Mongoose assigns each of your schemas an id virtual getter by default > which returns the documents _id field cast to a string, or in the case > of ObjectIds, its hexString.

So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId).

Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string). For example, if comparing id's, the string is probably better, as ObjectId's won't pass an equality test unless they are the same instance (regardless of what value they represent).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAri PoradView Question on Stackoverflow
Solution 1 - Javascriptjmar777View Answer on Stackoverflow