Connect Node.js project to a MongoDB (database)

In this article, we are going to connect MongoDB (database) into our Node.js project following each step clearly in a stepwise fashion. Before getting started if you have trouble in starting Node project and working with Git and GitHub have a look on those. However, we go through basic steps in general on the process. You have to install Node.Js and npm (installed on installing Node.Js).

Steps to Connect Node.js project to a MongoDB (database)

You already need to setup node environment in your device to proceed in this article to connect Node.Js to a MongoDB. Let's begin!

Step 1: Start node project - Create project folder and open the project in VS code. In the terminal give a command to begin new node project.
Check whether node installed or not in your device and its version.
    node -v

Then, begin node project
    npm init -y

Step 2: Install mongodb using editor terminal with the command;
    npm install mongodb

Check the version after installation and to check whether download or not.
    npm list mongodb

Step 3: Go to mongodb.com and Sign up (if no account already) or Sign in (if you already have).

Step 4: Build a new cluster for your node project where your data stores. Atlas managed the database for you. You can create free cluster (M0 cluster). It takes multiple steps you can proceed. Once cluster created you can load sample data from drop down menu in '- - -' button in right side of collections button.

Step 5: Now, lets connect the database to the project. Click on 'Connect' button. It would show how to get connected.

Set connection Security
- Add Connection IP Address.
- Create Database User and set password.

Choose a connection Method
- Click on 'Connect your Application'.
  * Chose 'Node.js' as Driver and copy the connection string.

Step 6: Let's get back to Code editor to create a script file say connectMongo.js do some code to connect the project to the mongodb using the connection string. The below given code helps to connect Node project with MongoDB. 
Note: uri should be the connection string obtained in proceed steps.

const { MongoClient } = require('mongodb'); async function main() { const uri = "mongodb+srv://db_user:pw_to_connect_Mongo@cluster0.wtyn3.mongodb.net/
                myFirstDatabase?retryWrites=true&w=majority"; const client = new MongoClient(uri); try { await client.connect(); await listDatabases(client); } catch (e) { console.error(e); } finally { await client.close(); } } main().catch(console.error); async function listDatabases(client) { const databasesList = await client.db().admin().listDatabases(); databasesList.databases.forEach(db => { console.log(`- ${db.name}`); }) }


I hope this would be helpful article to begin MongoDB in Node project. If any queries feel free to ask and wish for your kind suggestions and feedbacks.


0 Comments