In this Chapter , we will insert data in the "details" collection we created in the previous chapter.
Step - 1 : Including Packages
We will start by
requiring the package.
We are using the following package in our application :
var mongo = require('mongodb');
Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.
var new_db = "mongodb://localhost:27017/demo_db"
Step - 3 : Insert into DB
insertOne() is an inbuilt method which is used to insert data in the mongoDb
collection.
//insert_mongo_nodejs.js
mongo.connect(new_db , function(error , db){
if (error){
throw error;
}
var data = { name : "rishabhio" , age : "25" , mobile : "1234567890" }
db.collection("details").insertOne(data, (err , collection) => {
if(err) throw err;
console.log("Record inserted successfully");
console.log(collection);
});
});
D:\nj-learn-mongo>node insert_mongo_nodejs.js
D:\nj-learn-mongo>node insert_mongo_nodejs.js
Record inserted successfully
{ result: { ok: 1, n: 1 },
connection: null,
message: undefined,
ops:
[ { name: 'rishabhio',
age: '25',
mobile: '1234567890',
_id: 597073b2c6f60f5b3c23a1a5 } ],
insertedCount: 1,
insertedId: 597073b2c6f60f5b3c23a1a5
}