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

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

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

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.

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.

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 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

Now run the app.js using node

Running this command will show the record returned on screen.

No Responses