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.
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.
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.
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 });
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With