
Mongodb Get Started in NodeJs
Getting started with MongoDB in Node.js is super easy! Let me walk you through a simple "Hello MongoDB" project using both the native MongoDB driver and Mongoose, a popular ODM.
π Step-by-Step: Connect MongoDB with Node.js
β Option 1: Using the Native MongoDB Driver
π¦ Step 1: Install MongoDB driver
npm install mongodb
π Step 2: Basic MongoDB Connection & Insert
const client = new MongoClient(uri);async function run() { try { await client.connect(); const db = client.db('myDatabase'); const collection = db.collection('users'); // Insert a document const result = await collection.insertOne({ name: 'Alice', age: 25 }); console.log('Inserted ID:', result.insertedId); // Find the document const user = await collection.findOne({ name: 'Alice' }); console.log('Found User:', user); } catch (err) { console.error(err); } finally { await client.close(); }}run();
πͺ Option 2: Using Mongoose (Beginner Friendly)
π¦ Step 1: Install Mongoose
npm install mongoose
π Step 2: Connect, Define Schema & Use It
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 a modelconst User = mongoose.model('User', userSchema);// Insert & Find a userconst newUser = new User({ name: 'Bob', age: 30 });newUser.save() .then(() => User.findOne({ name: 'Bob' })) .then(user => { console.log('Found User:', user); mongoose.disconnect(); });
π§ Quick Tips
MongoDB automatically creates the database and collection the first time you insert data.
Use MongoDB Compass to view your local databases visually.
If you're using MongoDB Atlas, replace the URI with your cloud connection string.
π Whatβs Next?
Want to:
Build a full REST API?
Use MongoDB with Express.js?
Connect to MongoDB Atlas (cloud DB)?
Do CRUD, search, or pagination?