简体   繁体   中英

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 ie _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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM