Skip to content

Instantly share code, notes, and snippets.

@LearnWebCode
Created November 13, 2020 22:19
Show Gist options
  • Save LearnWebCode/49619dd621252bc116528ee64b9d67cc to your computer and use it in GitHub Desktop.
Save LearnWebCode/49619dd621252bc116528ee64b9d67cc to your computer and use it in GitHub Desktop.
Connect to MongoDB / Atlas within Netlify / AWS Lambda Serverless Function File
const mongodb = require("mongodb")
exports.handler = async function (event, context) {
const client = await mongodb.connect(process.env.CONNECTIONSTRING, { useUnifiedTopology: true })
const db = client.db()
try {
const dogs = await db.collection("pets").find({ species: "dog" }).toArray()
client.close()
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(dogs)
}
} catch (err) {
console.log(err)
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: "Please try again later."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment