AshKeys

Confessions and Confusions of a Freelance Fullstacker.

Ashok Mannolu Arunachalam, How toMongoDBNodeJS
Back

How to connect to MongoDB Atlas in NodeJS

I am trying to log some hit counts for this blog. For that, I am trying to understand and use MongoDB Atlas (with a free plan of course ^_^).

For that, I just followed their plan to connect to MongoDB which as follows:

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

This same can be used as a NodeJS server endpoint.