Serverless Node-Mongo API with DigitalOcean Functions

arpan45

Arpan Adhikari

Posted on August 29, 2022

Serverless Node-Mongo API with DigitalOcean Functions

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

Prerequisites:

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The Project folder will be created with the following directory structure:

node-mongo-serverless/
├── packages
│   └── sample
│       └── hello
│           └── hello.js
└── project.yml
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.

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}
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

doctl serverless deploy .
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
arpan45
Arpan Adhikari

Posted on August 29, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related