Database Integration (Mongoose vs ORMs)
Connecting Node.js to MongoDB using Mongoose and SQL using Prisma/Sequelize.
🧑🏫 Sabse pehle — simple mein samjho#
Node.js ko directly database se baat karni nahi aati. Iske liye hum beech mein ek "Translator" (Driver ya ORM/ODM) use karte hain. Agar database MongoDB (NoSQL) hai, toh sabse famous translator Mongoose hai. Agar database Postgres/MySQL (SQL) hai, toh aajkal Prisma ya Sequelize sabse zyada use hota hai. Ye tools humein SQL queries string mein likhne ke bajaye, seedha JavaScript objects ke through data save/fetch karne dete hain.
NoSQL: MongoDB with Mongoose (ODM)#
MongoDB is a document database (stores data as JSON-like objects). Mongoose is an Object Data Modeling (ODM) library that adds strict schemas and validations on top of MongoDB's flexible nature.
1. Connection#
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log('Connected to MongoDB!'))
.catch((err) => console.error('Connection failed', err));
2. Defining a Schema and Model#
A schema defines the shape of the document. The Model provides the interface to query the database.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 18 }
}, { timestamps: true }); // Automatically adds createdAt and updatedAt
const User = mongoose.model('User', userSchema);
3. Querying#
// Create
const newUser = await User.create({ name: "Tarun", email: "t@t.com", age: 25 });
// Read
const user = await User.findOne({ email: "t@t.com" });
const allUsers = await User.find({ age: { $gte: 20 } }); // Age >= 20
// Update
await User.findByIdAndUpdate(userId, { name: "New Name" }, { new: true });
SQL: PostgreSQL with Prisma (Modern ORM)#
While Sequelize is historically popular, Prisma has taken over the Node.js ecosystem (especially with TypeScript) due to its incredible developer experience and auto-generated types.
1. The Prisma Schema (schema.prisma)#
You define your database layout in a specific Prisma syntax, not in raw JavaScript.
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[] // Defines a one-to-many relationship
}
model Post {
id Int @id @default(autoincrement())
title String
authorId Int
author User @relation(fields: [authorId], references: [id])
}
2. Querying with Prisma Client#
After writing the schema, you run npx prisma generate, which creates a fully typed JavaScript client.
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
// Create a user and a post simultaneously (nested writes!)
const user = await prisma.user.create({
data: {
name: "Tarun",
email: "t@t.com",
posts: {
create: { title: "My first post" }
}
}
});
// Fetch all users and eagerly load their posts
const usersWithPosts = await prisma.user.findMany({
include: { posts: true }
});
Prisma handles the complex SQL JOIN statements for you behind the scenes!