Serverless Node-Mongo API with DigitalOcean Functions
Tags: javascript, serverless, tutorial, kubernetes
Published: 2022-08-29 19:20:18

Hello Folks,

We will discuss the newly launched **DigitalOcean Functions** - A way to go Serverless and will create a **node.js application** that can connect and store data to **MongoDB**. It's so simple to create a Serverless function with DigitalOcean. 

> Functions are blocks of code that run on demand without the need to manage any infrastructure. Develop on your local machine, test your code from the command line (using doctl), then deploy to App Platform — no servers required.

![DigitalOcean Serverless Functions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfk6q4dq6yf5zsl93uzd.png) 

Prerequisites:
- [DigitalOcean Account-$100 Free on signup](https://m.do.co/c/0eeab663047a)
- [Install doctl cli](https://docs.digitalocean.com/reference/doctl/how-to/install/)
- MongoDB Credentials(URI)


## Step 1: Init

Once you have setup and install doctl in your system. Check if everything is working by running the following command:

```
doctl serverless status
```
The above command should return something like this:

`Connected to function namespace 'fn-feb132ee-706a-4f13-9c81-f24a3330260a' on API host 'https://faas-nyc1-78edc.doserverless.co'`

Now initialise the project by running (node-mongo-serverless is our project name here, you can choose any preferable name):

```
doctl serverless init --language js node-mongo-serverless
```
The Project folder will be created with the following directory structure: 

```
node-mongo-serverless/
├── packages
│   └── sample
│       └── hello
│           └── hello.js
└── project.yml
```

Now we will rename the files and create a .env file in the root directory such that the new structure will look like the following:

```
node-mongo-serverless/
├── packages
│   └── mongodb
│       └── postData
│           └── index.js
└── project.yml
└── .env

```

## Step 2: Configure

Now we need to modify the `project.yml` file accordingly. It will be like the following. We need to modify package name and actions name.

```yml
targetNamespace: ''
parameters: {}
packages:
  - name: mongodb
    parameters: {}
    annotations: {}
    actions:
      - name: postData
        binary: false
        main: ''
        runtime: 'nodejs:default'
        web: true
        parameters: {}
        environment: {}
        annotations: {}
        limits: {}
environment:
  DATABASE_URL: ${MONGO_URI}
```

Now we will open and modify the .env file in the root folder with the MongoDB URI.

.env file will look something like the following. (Replace the value with your own MongoDB URI.)

```
MONGO_URI='mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/?authSource=admin'
```

Now we will run the following commands one by one:

```
cd node-mongo-serverless/packages/mongodb/postData
npm init -y
npm install --package-lock-only mongodb
```
The above commands will create `packages.json` file in the `node-mongo-serverless/packages/mongodb/postData` directory and add the mongodb package.

## Step 3: Add code to function

We can now create our main function in the index.js file we already have. 
First remove all the content of the index.js file and replace with the following code.

```javascript
const MongoClient = require('mongodb').MongoClient;

async function main() {
    const uri = process.env['DATABASE_URL'];
    let client = new MongoClient(uri);

    let data = { "name":"Arpan" };
    try {
        await client.connect();
        await client.db("namedb").collection("names").insertOne(data);
        console.log(`added ${data} to database.`);
        return { ok: true };
    } catch (e) {
        console.error(e);
        return {
            "body": { "error": "There was a problem adding the data to the database." },
            "statusCode": 400
        };
    } finally {
        await client.close();
    }
}

module.exports.main = main;
```
The function will add data to the MongoDB database. 
That's it. We are all done now. We can proceed to deploy our function now.

## Step 4: Deploy and Test the Function

We navigate to the root directory of the project where the project.yml is and run the following command to connect to the Serverless namespace.

```
doctl serverless connect
```
Once you get a positive response like "Connected to function namespace" you can run the following command to deploy the function.

```
doctl serverless deploy .
```
For the above command, you must be in the root directory of the project. You should see a success message about the deployment.

Run the following command to get the URL of the function API, where you can hit to store the data. 

```
doctl serverless functions get mongodb/postData --url
```

**You can copy and paste the returned URL into your local browser or postman or any other tool/package. you will receive the response from the index.js file if the data is inserted properly into MongoDB.**


Hope you enjoyed the article. For any queries feel free to ask in the comments.