Reputation: 11573
If I insert a document, directly with a mongodb client or with Mongoose, who is responsible to generate the _id
field's value? Is it happening inside the database engine or the clients do the work?
Upvotes: 0
Views: 33
Reputation: 522125
In MongoDB, each document stored in a collection requires a unique
_id
field that acts as a primary key. If an inserted document omits the_id
field, the MongoDB driver automatically generates anObjectId
for the_id
field.
Note
Most MongoDB driver clients will include the_id
field and generate anObjectId
before sending theinsert
operation to MongoDB; however, if the client sends a document without an_id
field, themongod
will add the_id
field and generate theObjectId
.
https://docs.mongodb.com/manual/core/document/index.html#the-id-field
Upvotes: 1