How do you connect Node.js to MongoDB? You typically use the MongoDB Node.js driver or an ODM like Mongoose. Basic connection example with native driver: const { MongoClient } = require('mongodb');
sync function connect() {
const uri = 'mongodb://localhost:27017/mydatabase';
const client = new MongoClient(uri);
try {
wait client.connect();
console.log('Connected to MongoDB');
const db = client.db('mydatabase');
// Use `db` to query collections
} catch (err) {
console.error(err);
} finally {
wait client.close();
}
}
connect();