
Mongodb Collection in NodeJs
Connecting to a MongoDB collection in Node.js is super straightforward with the MongoDB Node.js driver or an ODM like Mongoose.
Let’s look at both approaches 👇
📦 Option 1: Using Native MongoDB Driver
1️⃣ Install the MongoDB Driver
npm install mongodb
2️⃣ Connect and Access a Collection
const client = new MongoClient(uri);async function run() { try { await client.connect(); const db = client.db('myDatabase'); // Database name const collection = db.collection('users'); // Collection name // Example: Insert one await collection.insertOne({ name: 'Alice', age: 25 }); // Example: Find all const users = await collection.find().toArray(); console.log(users); } catch (err) { console.error(err); } finally { await client.close(); }}run();
🧙♂️ Option 2: Using Mongoose (Easier for Beginners)
1️⃣ Install Mongoose
npm install mongoose
2️⃣ Create Schema + Connect to DB
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(() => console.log('MongoDB connected!')) .catch(err => const userSchema = new mongoose.Schema({ name: String, age: Number});// Create model (maps to 'users' collection)const User = mongoose.model('User', userSchema);// Insert a userconst newUser = new User({ name: 'Bob', age: 30 });newUser.save().then(() => console.log('User added!'));// Find usersUser.find().then(users => console.log(users));
🧠 Quick Tips
A collection is like a table (in relational DBs).
You don’t need to "create" collections — MongoDB creates them when you insert data.
Use MongoDB Atlas for cloud-hosted databases.