MongoDB with NodeJs has a huge demand in the market. Mongodb is a NoSQL based database that is it is unlike SQL, SQL server traditional relational database with rows and columns but rather store database in the form of collections than tables, Each collection consists of JSON documents. In this tutorial, we will set up the MongoDB database, set up node application, connect them using mongoclient, perform CRUD operations. So, if you have never worked with node, MongoDB still you will be able to follow up and get at par with everyone. So, let’s get started!
1.Set Up MongoDB Database
The first step of nodejs with MongoDB tutorial is to set up the database server. Go to the link and download the community edition https://www.mongodb.com/download-center/community
While installing choose mongoDB
Run service as Network User and then, compass Community
To generate connection string, you need to create an account on https://cloud.mongodb.com/. Once, registered it will pick IP address, you have to give a username and password and it will generate connection string, similar to
Connect to compass GUI with connection string obtained as this connection string will also be used in node.js application
2.Node.Js Application Setup
then we need to create a folder, in that folder type npm init to initialize the repository as node.js application. you should see package.json file in the directory.
Create app.js file and type the following code
var msg=’Hello world!’;
Now, to run the application type node app.js
Now, you have successfully set up your node application. Now to connect to mongodb you need to install mongodb node.js driver that is mongoclient
On terminal, type
3. Create Collection in Database
Next step in mongodb with node.js tutorial is to create a database in mongodb, then create a collection under which we will Insert, Update, Delete records. Also, we will see how to first insert a data using the compass itself.
Here we have created engineerdiariesdb as database and users as collections
Insert 1 document into the collection
Under Add data insert document, add Json Object
4. Establish a connection with MongoDB
Replace your connection string, run using node app.js and if output on console is connected then you have successfully established connection with database MongoDB with nodejs.
5. Insert a record in MongoDB with nodejs
6. Update a record in MongoDB with nodejs
This will update record of name=priyanka, and set age to 22
7. Delete a record in MongoDB with nodejs
This will delete the record where name=priyanka
8. Record records in MongoDB with nodejs
This will output all the documents in the collection.
So, this was short and complete tutorial on mongodb with node.js crud operations.