Post Data to MongoDB serverless using Netlify Functions and AWS Lambdas

Quick and easy example showing how to create a Netlify function that will post data to a MongoDB instance

Wed, 01 Aug 2018

This tutorial is going to be very similar to yesterdays, so you may see some repeat code/content. We’re going to jump right into the code. In order to get this working we’re going to install both the co and mongoose packages using your package manager of choice.

npm install mongoose or yarn add mongoose

npm install co or yarn add co

Code

var co = require('co');
var mongoose = require('mongoose');

let conn = null;

const uri = 'mongodb://username:password@mongourl:port/databaseName';

exports.handler = function(event, context, callback) {
  const requestBody = JSON.parse(event.body);
  context.callbackWaitsForEmptyEventLoop = false;

  run(requestBody).
    then(res => {
      callback(null, res);
    }).
    catch(error => callback(error));
};

function run(requestBody) {
  return co(function*() {
    if (conn == null) {
      conn = yield mongoose.createConnection(uri, {
        bufferCommands: false,
        bufferMaxEntries: 0
      });
      conn.model('collectionName', new mongoose.Schema({
        schedule: String,
        occupancy: Number,
        count: Number,
        price: Number,
        time: String,
        link: String
      }));
    }

    const M = conn.model('Bookings');
    const doc = yield M.findOneAndUpdate({"collectionName": requestBody.schedule}, {$set:{count: requestBody.count}});
    console.log(doc)
    const response = {
      statusCode: 200,
      body: JSON.stringify(doc)
    };
    return response;
  });
}

If you want an in depth explanation of the code feel free to follow my example from yesterday where I explained how to get data from MongoDB with Netlify functions. The only difference in code is that your const doc variable will be making a request to find a specific entry and update using the findOneAndUpdate method. An example post request for your new lambda would be

          axios.post('/.netlify/functions/postSchedule', update).then(res => {
            this.setState({success: true});
          })

As you can see, nothing changes in how you would code your friend end to make a post request! Tomorrow I will show an example for another function, this time we will be integrating our lambda with Stripe to make payments without a backend.

Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge