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 -DCreate 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!