Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between id and _id in mongoose?

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

like image 431
Ari Porad Avatar asked Mar 30 '13 22:03

Ari Porad


People also ask

What is 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.

What is the difference between _id and id?

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.

What is _id in Mongoose?

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 _id in MongoDB?

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.


1 Answers

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

like image 199
jmar777 Avatar answered Sep 28 '22 08:09

jmar777