What is the difference between _id
and id
in mongoose? Which is better for referencing?
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.
The _id field is the default field for Bson ObjectId's and it is,by default, indexed. _id and id are not the same. You may also choose to add a field called id if you want, but it will not be index unless you add an index. It is just a typo in the docs.
Sep 3, 2019. By default, MongoDB creates an _id property on every document that's of type ObjectId. Many other databases use a numeric id property by default, but in MongoDB and Mongoose, ids are objects by default.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With