What is the difference between id and _id in mongoose?

39,944

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).

Share:
39,944
Ari Porad
Author by

Ari Porad

Updated on August 02, 2020

Comments

  • Ari Porad
    Ari Porad almost 4 years

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

  • Ari Porad
    Ari Porad about 11 years
    please see revised question
  • jmar777
    jmar777 about 11 years
    As far as 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).
  • Lucky Soni
    Lucky Soni over 9 years
    @jmar777 The ObjectId does have an equals method which can be used for comparison.
  • Elad Nava
    Elad Nava over 8 years
    Watch out for nested documents. Mongoose won't assign the id virtual to nested objects, even though they have an _id field with an ObjectId.
  • AlxVallejo
    AlxVallejo over 8 years
    @EladNava Does that mean if you want one document to reference another, you should assign a custom field the model that references the _id field?
  • Elad Nava
    Elad Nava over 8 years
    @AlxVallejo Not necessarily, you just need to read from the _id field yourself and convert it from an ObjectId to a string.
  • Woppi
    Woppi almost 6 years
    So in short book.id === string and book._id === ObjectId, just putting this out for future reference :)