Created
September 21, 2024 06:31
-
-
Save paulweezydesign/303e1499ffcdf90548be252078279461 to your computer and use it in GitHub Desktop.
a snippet to get data from mongodb in a serverless function
This file contains hidden or 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
import { MongoClient } from 'mongodb'; | |
const uri = 'mongodb+srv://weezy:[email protected]/?retryWrites=true&w=majority'; | |
const client = new MongoClient(uri); | |
async function handler(req, res) { | |
if (req.method === 'GET') { | |
try { | |
await client.connect(); | |
const database = client.db('kittens'); | |
const collection = database.collection('kittens'); | |
const data = await collection.find({}).toArray(); | |
res.status(200).json(data); | |
} catch (error) { | |
res.status(500).json({ error: 'Error connecting to the database' }); | |
} finally { | |
await client.close(); | |
} | |
} else { | |
res.status(405).json({ error: 'Method not allowed' }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment