Reputation: 494
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
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.
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.
In react in your component (in this example I use react):
That's all. I hope this help you.
Upvotes: 5