Jenny
Jenny

Reputation: 494

Connect Mongoose and AWS Lambda Functions

I want to use lambda functions with Netlify and Mongoose. Basically triggering a function on the frontend and updating the DB.

const mongoose = require('mongoose')

let uri = 'mongodb+srv://...flashcard?retryWrites=true&w=majority'

let client = mongoose.connect(`${uri}`, {
  useNewUrlParser: true
}
);

const clientPromise = client.connect()

exports.handler = async (event, context, callback) => {
 
  context.callbackWaitsForEmptyEventLoop = false;
  
  try {    
 
    client = await clientPromise;
    client.db('flashcards').createCollection('hello')

    return {
      statusCode: 200,
    };
  } catch (err) {
    return {
      statusCode: 500,
      body: JSON.stringify({ msg: err.message }) 
    };
  }
}

This does not work and returns

500 Internal Server Error Cannot read properties of undefined (reading 'connect')

However, if I do it with the MongoClient and just change the first part, it works and updates the DB.


const { MongoClient } = require('mongodb');


let uri = 'mongodb+srv://...flashcard?retryWrites=true&w=majority'
let client = new MongoClient(`${uri}`, {
  useNewUrlParser: true
}
);

How could I do it with mongoose? Thanks for reading!

I took the working example from

https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/

Upvotes: 1

Views: 3328

Answers (1)

Jurek
Jurek

Reputation: 66

This is how I did it. I used react.js and deployed simple website on Netlify to check how their serverless functions are working. In this example I just send email from form and save its data in mongo atlas database and I use mongoose.

  1. Prepare altas mongo url to connect to their database. You will need to add environmental variable on netlify website, in settings on your deployed project or you can do it before your deploy.
  2. In the root directory of your project:
  • Create folder db > conntectDb.js file

  • In conntectDb.js file

      const mongoose = require('mongoose');
      const connectDb = async (url) => {
    
       //Here you can observe that url of mongo atlas will show once
       //Check this in netlify functions panel after you deploy your page
       //Observe it when you send form using url netlify function
      console.log(url, 'url to mongo atlas, connectDb');
    
       await mongoose.connect(url);
      };
    
      module.exports = connectDb;
    
  • Create folder models > email.js file

  • In email.js file create schema for email

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const emailSchema = new Schema({
     name: {
      type: String,
      required: true,
     },
     email: {
      type: String,
      required: true,
     },
     message: {
      type: String,
      required: true,
     },
    });
    
    module.exports = mongoose.model('Email', emailSchema);
    
  • Create folder netlify > folder functions > email.js file

  • Here to keep netlify functions

  • Info about structure of folders when adding netlify functions to project you can find here: https://docs.netlify.com/functions/build-with-javascript/

  • In email.js file

    const mongoose = require('mongoose');
    const connectDb = require('../../db/connectDb');
    const Email = require('../../models/email');
    
    connectDb(process.env.REACT_APP_DB);
    //Make connection with mongoose to mongo atlas outside handler
    
    exports.handler = async function (event) {
     //Observe state connection for mongoose in
     //Netlify functions panel on their website when you deploy your   page
     console.log(mongoose.connection.readyState, 'Ready state email');
     const body = JSON.parse(event.body);
     const newEmail = await Email.create(body);
    
     return{
      statusCode: 200,
      body: JSON.stringify({ value: newEmail }),
     };
    };
    

Note: I that added conntection mongoose (connectDb) outside the function handler.

  • First time mongoose.connection.readyState will show '2' for it, which means 'connecting' to database.
  • Later will show '1' which means 'connected'
  • This can prevent all the time connecting to database.
  • Info: Check connection readyState
  • https://mongoosejs.com/docs/api/connection.html#connection_Connection-readyState
  • You can observe logs in functions panel of your project in netlify when you call url this function,

In react in your component (in this example I use react):

  • create form with inputs for name,email,message
  • Use for example fetch api to send request
  • Send POST http request
  • Use this url const url = '/.netlify/functions/email';
  • If you follow my folder structure in this example

That's all. I hope this help you.

Upvotes: 5

Related Questions