What is the difference between id and _id in mongoose?
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).
Ari Porad
Updated on August 02, 2020Comments
-
Ari Porad almost 4 years
What is the difference between
_id
andid
in mongoose? Which is better for referencing? -
Ari Porad about 11 yearsplease see revised question
-
jmar777 about 11 yearsAs far as what's better for referencing, that depends entirely on the context (i.e., do you want an
ObjectId
or astring
). For example, if comparingid
's, the string is probably better, asObjectId
's won't pass an equality test unless they are the same instance (regardless of what value they represent). -
Lucky Soni over 9 years@jmar777 The ObjectId does have an
equals
method which can be used for comparison. -
Elad Nava over 8 yearsWatch 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 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 over 8 years@AlxVallejo Not necessarily, you just need to read from the
_id
field yourself and convert it from anObjectId
to astring
. -
Woppi almost 6 yearsSo in short book.id === string and book._id === ObjectId, just putting this out for future reference :)