...

Getting Started with MongoDB and Mongoose in Node.js

Learn how to connect MongoDB with Node.js using Mongoose, define schemas, perform advanced queries, and manage data with ease.

πŸš€ Getting Started with MongoDB and Mongoose in Node.js

MongoDB is a powerful NoSQL database, and Mongoose is an ODM (Object Data Modeling) library that simplifies working with MongoDB in Node.js.

In this guide, you’ll learn:
βœ… Write clean and efficient database logic
βœ… Perform queries using filters, sorting, projection, and comparison operators
βœ… Define Mongoose schemas and models
βœ… How to connect MongoDB with Node.js

 npm i mongoose
 npm i nodemon -D

Create index.js  file and add below code

🧩 Step 1: Connect to MongoDB

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/test')
.then(() => {
  console.log('MongoDB Connected Successfully');
})
.catch((err) => {
   console.log('MongoDB Connection Failed', err);
   process.exit(1);
});



πŸ—οΈ Step 2: Define a Schema and Model

const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
isMarried: Boolean,
sallary: Number,
gender: String
});

const User = mongoose.model('User', userSchema);



πŸ” Step 3: Querying the Database

async function fetchUsers() {
const users = await User.find()
.and([{ isMarried: true }, { age: 28 }])
.select('name age isMarried');

console.log(users);
}

fetchUsers();


🧠 Query Examples

πŸ”Ή Find Queries


await User.findOne({ isMarried: false });
await User.find({ isMarried: false }).select('name email sallary');
await User.find({}).select('-name -email');



πŸ”Ή Sorting and Limiting


await User.find().sort('sallary');
await User.find().sort('-sallary').limit(2);



πŸ”Ή Count Documents

await User.find().countDocuments();



βš–οΈ Comparison Operators
Operator Usage Example

Operator Description Example
$eq Equal to { age: { $eq: 30 } }
$ne Not equal to { age: { $ne: 30 } }
$gt Greater than { age: { $gt: 30 } }
$gte Greater than or equal to { age: { $gte: 30 } }
$lt Less than { age: { $lt: 30 } }
$lte Less than or equal to { age: { $lte: 30 } }
$in Value in list { age: { $in: [30, 35, 40] } }
$nin Value not in list { age: { $nin: [18, 22] } }


πŸ”— Logical Operators

await User.find()
.and([{ isMarried: true }, { age: 28 }])
.select('name age isMarried');

await User.find()
.or([{ age: 30 }, { gender: 'female' }]);


βž• Create a New User (Optional)

async function CreateUser(name, age, email, isMarried, sallary, gender) {
  const user = new User({
    name,
    age,
    email,
    isMarried,
    sallary,
    gender,
  });

  await user.save();
  console.log(`${user.name} Created Successfully`);
}

// Example usage:
// CreateUser('Mike Davis', 40, 'mikedavis@gmail.com', true, 80000, 'male');


πŸ“¦ Packages Required


Install Mongoose with:
npm install mongoose
πŸ”„ Update a User by ID

You can update a document using either findById and save(), or findByIdAndUpdate():


// Method 1: Find by ID and then update fields
const users = await User.findById('688e453dca90f7632dc68b2e');
users.name = 'John Doe';
await users.save();


// Method 2: Directly update using findByIdAndUpdate
const updatedUser = await User.findByIdAndUpdate(
  '688e453dca90f7632dc68b2e',
  { age: 55 },
  { new: true } // Return the updated document
);

console.log(updatedUser);

πŸ—‘οΈ Delete a User by ID

To remove a document by its ID:
// πŸ—‘οΈ Delete a user by ID
const users = await User.findByIdAndDelete('688e453dca90f7632dc68b2e');
console.log(users); // Logs the deleted document (or null if not found)

// ❌ Delete a single user by condition
const users = await User.deleteOne({ name: 'John Doe' });
console.log(users); // Logs { acknowledged: true, deletedCount: 1 }

// 🚫 Delete multiple users with age β‰₯ 30
const users = await User.deleteMany({ age: { $gte: 30 } });
console.log(users); // Logs { acknowledged: true, deletedCount: X }

Notes:


findByIdAndDelete(id) β†’ Deletes one document by its _id, and returns the deleted document.

deleteOne(filter) β†’ Deletes the first document that matches the filter. Returns { deletedCount: 1 }.

deleteMany(filter) β†’ Deletes all documents matching the filter. Returns { deletedCount: N }.


βœ… Conclusion

With Mongoose, managing MongoDB becomes much simpler in Node.js. You’ve learned how to:

Connect and handle MongoDB connections

Define schemas and models

Perform filtering, sorting, projection, and complex queries

Use comparison and logical operators effectively
Let me know if you want a follow-up blog on CRUD operations, MongoDB Atlas, or API integration with Express.js!

William Anderson

I am a versatile Full-Stack Web Developer with a strong focus on Laravel, Livewire, Vue.js, and Tailwind CSS. With extensive experience in backend development, I specialize in building scalable, efficient, and high-performance web applications.