In this Chapter , we will Read the first occurance of the data from the mongoDb collection "details".
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 : Read From DB
findOne() is an inbuilt method which is used to Read the first
occurance of the data from the mongoDb
collection.
//read-first-occurance-mongodb-nodejs.js
mongo.connect(new_db , function(error , db){
if (error){
throw error;
}
//findOne() reads the first occurance of any data from the database.
db.collection("details").findOne({}, (err , collection) => {
if(err) throw err;
console.log("Record Read successfully");
console.log(collection);
db.close();
});
});
D:\nj-learn-mongo>node read-first-occurance-mongodb-nodejs.js
D:\nj-learn-mongo>node read-first-occurance-mongodb-nodejs.js
Record Read successfully
{ name: 'Nodejsera',
age: '23',
mobile: '9876543210',
_id: 59706a56a4f6761e3cc22c98 }