What is MongoDB?
MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents.
Connecting to MongoDB
javascript
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true
});Defining Schemas with Mongoose
javascript
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
age: {
type: Number,
min: 0,
max: 120
},
isActive: {
type: Boolean,
default: true
},
role: {
type: String,
enum: ['user', 'admin', 'moderator'],
default: 'user'
}
}, {
timestamps: true
});
const User = mongoose.model('User', userSchema);CRUD Operations
Create
javascript
const user = await User.create({
name: 'John Doe',
email: 'john@example.com',
age: 30
});Read
javascript
// Find all
const users = await User.find();
// Find with filter
const activeUsers = await User.find({ isActive: true });
// Find one
const user = await User.findOne({ email: 'john@example.com' });
// Find by ID
const user = await User.findById('userId');Update
javascript
// Update one
await User.updateOne(
{ _id: userId },
{ name: 'Jane Doe' }
);
// Find and update
const user = await User.findByIdAndUpdate(
userId,
{ age: 31 },
{ new: true }
);Delete
javascript
await User.findByIdAndDelete(userId);Query Operators
javascript
// Comparison
await User.find({ age: { $gte: 18, $lte: 65 } });
// Logical
await User.find({
$or: [
{ role: 'admin' },
{ age: { $gte: 21 } }
]
});
// Array operations
await User.find({ tags: { $in: ['javascript', 'nodejs'] } });Aggregation
javascript
const result = await User.aggregate([
{ $match: { isActive: true } },
{ $group: { _id: '$role', count: { $sum: 1 } } },
{ $sort: { count: -1 } }
]);Best Practices
- 1Use indexes: Speed up queries
- 2Validate data: Use schema validation
- 3Use lean(): For read-only operations
- 4Handle errors: Always use try/catch
- 5Use transactions: For multi-document operations
Conclusion
MongoDB with Mongoose provides a powerful, flexible solution for NoSQL data storage.