Created
November 13, 2020 22:19
-
-
Save LearnWebCode/49619dd621252bc116528ee64b9d67cc to your computer and use it in GitHub Desktop.
Connect to MongoDB / Atlas within Netlify / AWS Lambda Serverless Function File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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