Connect Express JS Server with Mongo DB

Chanuka Dinuwan
1 min readDec 19, 2022

--

Express JS backend and Mongo DB

To connect an Express.js app to a MongoDB database, you must first install the Node.js MongoDB driver and then require it in your app.

  1. Install the MongoDB driver for Node.js by running the following command:
npm install mongodb

2. Add the following code to your Express.js server file to import the MongoDB driver and create a connection to your MongoDB instance.

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});

Replace <username> and <password> with the username and password for your MongoDB instance.

3. Once connected, you can perform operations on the MongoDB database such as inserting, updating, and retrieving data.

Here’s an example of how you can insert a document into a collection:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
collection.insertOne({ name: "Samsung Galaxy S10" }, function(err, result) {
console.log("Inserted document into the collection");
client.close();
});
});

For more details: https://www.mongodb.com/home

--

--

Chanuka Dinuwan
Chanuka Dinuwan

Written by Chanuka Dinuwan

Software Engineer | Cloud | DS & AI Enthusiast

No responses yet