Skip to content

Instantly share code, notes, and snippets.

@paulweezydesign
Created September 21, 2024 06:31
Show Gist options
  • Save paulweezydesign/303e1499ffcdf90548be252078279461 to your computer and use it in GitHub Desktop.
Save paulweezydesign/303e1499ffcdf90548be252078279461 to your computer and use it in GitHub Desktop.
a snippet to get data from mongodb in a serverless function
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