Septiana Yoga
Septiana Yoga

Reputation: 41

Mongodb insertOne changing the data?

I was learning to insert data into mongodb, here is the code:

console.log(this.data) //first
userCollection.insertOne(this.data)
console.log(this.data) //second

The first log:

{username: aaa, password: aaa}

The second log:

{username: aaa, password: aaa, _id: some_id_here}

Where is _id from?

Does mongodb change data or does it is work like callback?

Like when we insert data in mongodb it sends the data that has been inserted back?

Upvotes: 2

Views: 831

Answers (4)

Ahsath
Ahsath

Reputation: 453

All the other answers are correct but they fail to explain why this happens in the first place.

If you check the Node.js MongoDB Driver API for the insertOne method you will notice that there is a property you can pass into the option object called forceServerObjectId, what this does and I am quoting:

Force server to assign _id values instead of driver.

and by default is set false.

So, if you are using the driver:

If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document.

This behavior can be overridden by setting the forceServerObjectId property to true.

Boom, there you go

Upvotes: 3

Sa1
Sa1

Reputation: 41

_id is a unique value generated for every inserted document in mongoDB. It is treated as a primary key.

Upvotes: 0

Natapon Sripetchpun
Natapon Sripetchpun

Reputation: 11

it's a ObjectId. Generate By default for every document. So every document will have it.

Upvotes: 0

Subburaj
Subburaj

Reputation: 5192

_id is the unique id created by mongoDB. SO that each and every document will have this.

Refer https://docs.mongodb.com/manual/core/document/

Upvotes: 1

Related Questions