Because Node.js natively handles JSON data, MongoDB—a document-oriented NoSQL database that stores data in BSON (Binary JSON) format—is the most popular database paired with Node.js. Mongoose acts as the schema-based Object Data Modeling (ODM) layer that enforces structure, validation, and business logic.
// db.js
const mongoose = require('mongoose');
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/veewom_db', {
maxPoolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000 // Keep trying to send operations for 5 seconds
});
console.log(`[MongoDB Connected] Host: ${conn.connection.host}`);
} catch (err) {
console.error('MongoDB connection error:', err.message);
process.exit(1); // Exit process with failure
}
};
module.exports = connectDB;
models/User.jsconst mongoose = require('mongoose');
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, 'User name is required'],
trim: true,
maxlength: [50, 'Name cannot exceed 50 characters']
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true, // Creates a unique index in MongoDB!
lowercase: true,
match: [/\S+@\S+\.\S+/, 'Please provide a valid email']
},
role: {
type: String,
enum: ['student', 'instructor', 'admin'],
default: 'student'
},
enrolledCourses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Course' // Reference to Course model for population
}
]
},
{
timestamps: true // Automatically creates createdAt and updatedAt fields
}
);
// Database index on email and role for lightning-fast queries
userSchema.index({ email: 1, role: 1 });
module.exports = mongoose.model('User', userSchema);
const User = require('./models/User');
// 1. CREATE
async function createUser(userData) {
const user = await User.create(userData);
return user;
}
// 2. READ (with Query Filtering & Population)
async function getStudentsWithCourses() {
return await User.find({ role: 'student' })
.select('-__v') // Exclude version key
.populate('enrolledCourses') // Join course documents!
.sort({ createdAt: -1 }) // Newest first
.limit(20);
}
// 3. UPDATE
async function updateUserEmail(userId, newEmail) {
return await User.findByIdAndUpdate(
userId,
{ email: newEmail },
{ new: true, runValidators: true } // Returns updated doc & runs validation
);
}
// 4. DELETE
async function deleteUser(userId) {
return await User.findByIdAndDelete(userId);
}
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Compare NoSQL MongoDB with relational SQL databases.
Connect Mongoose models to Express controllers.
Cache high-traffic Mongoose database queries.