In this part of the mongodb operations using node.js tutorial series , we will insert data in
mongodb collection using Node.js
.
We will start by including mongodb
npm package as shown below :
var mongo = require('mongodb');
Establish a connection between the mongoDb database and our node.js app using the following :
var new_db = "mongodb://localhost:27017/demo_db"
insertOne()
is an inbuilt method which is used to insert data in mongodb collection
as shown below:
//insert.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db";
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);
});
});
>node insert.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
}
In this article we learned about
monogdb
npm package in your app.