MongoDB
Beginner
1 min read
Installing and Connecting to MongoDB
Example
// Install MongoDB Node.js driver
npm install mongodb
// Connect with the native driver (Node.js)
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function main() {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db('myAppDB');
const users = db.collection('users');
// Quick ping to verify connection
await db.command({ ping: 1 });
console.log('Ping successful');
// Always close the connection when done
await client.close();
}
main().catch(console.error);
// .env file (never commit this)
// MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/myAppDB