segmentationfaulter
segmentationfaulter

Reputation: 1045

Why do the insertOne method from mongodb node.js driver mutates the object to be inserted?

I am learning mongodb with node, and I was playing with the following code

var assert = require('assert')
var url = 'mongodb://localhost:27017/learnyoumongo'
var client = require('mongodb').MongoClient

var doc = {
  firstName: 'Steve',
  lastName: 'Smith'
}
console.log(doc)  //logs as expected
client.connect(url, (err, db) => {
  assert.equal(err, null)
  var docs = db.collection('docs')
  docs.insertOne(doc, (err, result) => {
    assert.equal(err, null)
    console.log(doc)  //logs with an extra property i.e. _id
    db.close()
  })
})

I was surprised to see that doc is mutated by mongo, look at inspect the output of both of the console.log statements. Why is the doc object mutated.

Upvotes: 7

Views: 3876

Answers (1)

piemonkey
piemonkey

Reputation: 751

Mongo adds an automatically generated _id to every document that doesn't define one itself. This is a special object type called an ObjectId and is used as a primary key. You can see the details of the format here.

You can get around the auto-generated _id by adding your own to each object but you'll need to be able to guarantee that they're unique as if you try to store two objects with the same _id you'll get a duplicate key error.

Upvotes: 4

Related Questions