DEV Community

Cover image for Building a Serverless REST API using MongoDB(mongoose), NodeJs and Serverless framework
Nicolas Lima
Nicolas Lima

Posted on

Building a Serverless REST API using MongoDB(mongoose), NodeJs and Serverless framework

Goals

Build and test locally a Serverless API, that can access a local MongoDB using mongoose

Requirements

All right fellows, first I need to explain the reason that I created this post. I'm a young BackEnd developer, and I've encountered a lot of information about the creation of Serverless API's, but I realized a great lack of articles when it comes to build using mongoose and testing locally. Anyway, this is a quite simple tutorial, but if you're just like I was yesterday, maybe it can save you some hours.

This lesson is specific for people who already know almost everything to set up this API, but is suffering because of two or three poorly explained things. So, if you don't know how to set up your AWS account, or don't know how to use the serverless framework, here are some videos that helped me:
How to create and deploy a simple Serverless API
Understanding a little bit more about AWS LAMBDA
Installing MongoDB

Let's go to work!

Ok, So let's start installing the Serverless package:

npm install -g serverless 
Enter fullscreen mode Exit fullscreen mode




Now let's create a default service using the aws-nodejs template


sls create -t aws-nodejs -p api && cd api
Enter fullscreen mode Exit fullscreen mode




Now you can see inside the folder we just created named 'api', that we have 2 files:'handler.js' and 'serverless.yml'

Now, inside your api folder, let's initialize npm

npm init
Enter fullscreen mode Exit fullscreen mode




Now, let's install mongoose


sudo npm install mongoose --save
Enter fullscreen mode Exit fullscreen mode




Ok guys, above, in the "Requirements" session, I recommended this Video, it will explain how the basic function inside our file works, re-watch if you feel needs, because we're gonna apply some changes on those files.

First, make sure you run "mongod" command, because we need a local MongoDB service.

Okay... Now, let's create a new folder inside our api directory, let's name it "Schemas", inside it we're gonna create a new Schema for our MongoDB, if you're not used to work with schemas, check this mongoose Doc about them

(inside our directory named 'api') mkdir schemas 
Enter fullscreen mode Exit fullscreen mode




Then


(inside schemas) touch user.js
Enter fullscreen mode Exit fullscreen mode




Using some editor(I like Atom), edit user.js structure inside a var and export a module with this one

Just like this

All right, now inside "handler.js" let's modify the same "hello" function to connect with our running Mongod service and execute a simple query, but before we need to import "mongoose", start a connection, get our userSchema and create a model.

(inside handler.js) var mongoose = require("mongoose");
Enter fullscreen mode Exit fullscreen mode




Then


var connectorMongodb =  mongoose.connect('mongodb://localhost/mynewDB');
Enter fullscreen mode Exit fullscreen mode




Almost there...


var userSchema = require('../api/schemas/userSchema.js');
Enter fullscreen mode Exit fullscreen mode




Okay...


var userModel = mongoose.model('user',userSchema,'user');
Enter fullscreen mode Exit fullscreen mode




Just to remember you guys, this lesson isn't for total beginners, so if you don't know how to use mongoose and what is a model or schema, go work on it first. This lesson is specific for people that are getting into trouble because of the lack of information about create a Serverles Rest API using specifically mongoose.

Ok, now let's apply some changes inside our "handler.js", and remember that we must close our mongoose connection once it was open, otherwise our function will "timeout" (Lambda functions have a default amount of seconds until it stops)

Like this

Now, inside your api directory, run this command in order to test your function "hello" locally

sls invoke local --function hello
Enter fullscreen mode Exit fullscreen mode




It should returns you a Json with your user's collection information

I guess you should already have some user data stored inside your DB, just go to mongoshell and use db.user.insert

I hope i helped you guys, see you later.

My Instagram if you like to discuss anything with me

Top comments (3)

Collapse
 
jaydestro profile image
Jay Gordon

Hey Nicolas, I love this blog post - I work at MongoDB and want to help you out with some ideas. I will try to reach you on instagram, but feel free to email me directly so we can discuss how I can help you expand the reach of this blog post.

Collapse
 
delimanicolas profile image
Nicolas Lima • Edited

Thanks a lot, it's very nice to receive such a message from the guy who once taught a lot about Mongodb. I'm currently thinking about write a new post explaining how (Node, Mongo and React) helped me with my first experience running my own business. So it's gonna be great if you can give me some tips. See you mate!

Collapse
 
carletto10 profile image
Carletto10

Hi Nicolas, Great tutorial!!!

I'm migrating an express application to serverless application so in my controller folder where I do the connection to MongoDb I dont have access to contex variable to use this code line 'context.callbackWaitsForEmptyEventLoop = false'

Is there any way to access to this variable or I need to move all the connections to handler.js file

Thanks for read