Node Js, MongoDb select record with findOne

Node Js, MongoDb select record with findOne

To select a single record from mongoDB database using  findOne() function  in Node Js

var MongoClient = require('mongodb').MongoClient;
//Open the connection to server

MongoClient.connect('mongodb://localhost:27017/test', function(err, db){
        if(err) throw err;
        db.collection('people').findOne({}, function(err, doc){
        if(err) throw err;
        console.log(doc);
        db.close();
     });
     console.dir("Called findOne");

});

In the code below we use require function to include the  module ‘mongodb’.MongoClient and is assigned to a variable MongoClient

var MongoClient = require('mongodb').MongoClient;

After including mongodb module we have to connect to the server. Consider the code below

MongoClient.connect('mongodb://localhost:27017/test', function(err, db){
      if(err) throw err;

In the line above we have connected to to local server on port 27017 to ‘test’ database then next is an anonymous function that accepts error and the database pointer that is pointing to test database. If there is an error, then error will be thrown and program will not run further otherwise consider  code below.

 db.collection('people').findOne({}, function(err, doc){
     if(err) throw err;
     
      console.log(doc);
      db.close();

In the code first line, we are using db object’s collection method specifying required collection name, findOne() method is used for getting a single record from the collection.

Inside findOne we pass two parameters

1. empty braces {} Thse empty braces represent a condition ( Where clause in Relational DBMS). This condition is empty or we are not specifying any condition yet.

2. An anonymous function that contains err object and doc returned from database.

 db.collection('people').findOne({}, function(err, doc){

if there is some error  then error will be  thrown other wise the document found will be passed to console.log function and db connection will be closed.

 if(err) throw err;
      console.log(doc);
      db.close();

if Node Js  and MongoDB is installed on your system then copy this code and create a new file named app.js. This program assumes that you have installed ‘mongodb’ module. If not then need to install ‘mongodb’ module first using npm or  Node Package Manager

npm install mongodb

Now run the app.js using node

> node app.js

Running this command will show the record returned on screen.

No Responses