Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 513
segmentationfaulter Avatar asked Sep 29 '15 16:09

segmentationfaulter


People also ask

How to use insertOne in NodeJS?

You can insert multiple documents using the collection. insertMany() method. The insertMany() takes an array of documents to insert into the specified collection. You can specify additional options in the options object passed as the second parameter of the insertMany() method.

Which drivers are useful to connect node js with MongoDB?

Connect your Node. js applications to MongoDB and work with your data using the Node. js driver. The driver features an asynchronous API that you can use to access method return values through Promises or specify callbacks to access them when communicating with MongoDB.

Which method is used to connect from NodeJS to MongoDB?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

Which method of Mongoose helps to insert one record of a specific model into a collection?

The create() method is similar to the insert() method. It is used to insert a single document in a collection. Let's understand the create() method with the help of an example.


1 Answers

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.

like image 136
piemonkey Avatar answered Nov 14 '22 23:11

piemonkey