Node With AWS DocumentDB using Mongoose

Rishabh Garg
3 min readMay 5, 2022

In this article, I am using Mongoose ORM to connect with MongoDB in the Lambda Node application.

I created a prototype of the NodeJS application to connect with MongoDB that is working fine on local. So I thought to move it to production and I tried to setup MongoDB using the following approaches(mentioned my finding)

  1. MongoDB on AWS EC2
  2. MongoDB Atlas
  3. Document DB

In Approach 1, I have more costs for EC2 Instance. For this approach, I need to do all chores like database backup, replication, and sharding.

Now, when I tried Approach 2, I don’t need to do all chores(manual backup, replication, and other administrative Jobs) which are required in Step 1 but here my API started taking time and I was not happy with this performance lack.

Then I tried Approach 3 but find it difficult to implement this because I didn’t find any good article to implement this. So here I mention all the points which I need to connect Document DB from mongoose using NodeJS lambda.

Here I have Node Lambda Already Deployed inside the default VPC and default security group. My default Security group allows all traffic for now.

Setps to Setup DocumentDB

  1. Login to the AWS console and navigate to Amazon Document DB
Amazon DocumentDB Home

2. Click on Create Cluster, It will open Create Cluster page, where you can define your cluster configuration like cluster name, number of instances, and user information for cluster authentication.

You can also change the advanced settings(like Network settings(VPC, subject, and security group), Backup, and Encryption) of this cluster if you want to. Here I updated only the security group under Network Settings.

3. I created a new Security group for DocumentDB which have an inbound rule for port 27017 and source is default security group. ( here I have the DocumentDb cluster in the same VPC but keep the cluster in a private subnet)

4. Once, Your cluster is created, you can see the following details

All done from the AWS console side.

Now we need to change our code to connect with DocumentDB. Please Copy the connection string and paste into the given gist

All Done. Now once you deploy this code you can see “MongoDB Connection Successful” when you test your lambda.

Here, I just want to share my finding which I tried to connect with DocumentDB. Maybe I missed some points. You are welcome for suggestions.

References:

  1. https://fitdevops.in/how-to-create-and-use-aws-document-db/
  2. Get Started with Amazon DocumentDB — Amazon DocumentDB

3. Mongoose v6.3.2: Mongoose Tutorials: SSL Connections (mongoosejs.com)

Big Thanks For Reading & Happy Learning !!!

--

--

Rishabh Garg

Full Stack Developer #Data Structure #JavaScript #MongoDb #Alogorithms #Angular #Node #Mean Stack Developer #Websocket #Ionic #IndexedDB #Html #Css #Scss