Gebruik in Express.js
Connect per request
import { MongoClient } from "mongodb";
const client = new MongoClient("mongodb://localhost:27017");
const app = express();
app.get("/students", async (req, res) => {
try {
await client.connect();
const db = client.db("example");
const students = await db.collection("student").find().toArray();
res.json(students);
} catch (error) {
console.error(error);
res.status(500).send("Internal server error");
} finally {
await client.close();
}
});Database module
Collections exporteren
Database vullen bij opstart
Data ophalen in routes
Alles samen
Environment variabelen
Laatst bijgewerkt