Theory
Backend को एक Shape दीजिए
FestConnect अब real data save करता है: users, events, registrations। जैसे ही data और logic grow होते हैं, एक one-file server एक mess बन जाता है। एक well-structured backend दो concerns separate करता है: data कैसा दिखता है (models) और हर route पर क्या होता है (controllers)।
Database के लिए, FestConnect MongoDB इस्तेमाल करता है (जिससे आप Sem 5 में मिले) Mongoose नाम की एक library के through, जो data shapes define करती है और clean create-read-update-delete methods देती है। यह lesson models, controllers, और Mongoose के साथ CRUD cover करता है, तो backend grow होने के साथ organised रहे।
Theory
Mongoose के साथ Models
Mongoose Node में MongoDB के लिए एक ODM (Object Data Modelling) library है। आप अपना data एक Schema से describe करते हैं, fields और इनके types, और इसे एक Model में compile करते हैं। Model उस collection का आपका gateway है: आप इसे documents create और query करने के लिए इस्तेमाल करते हैं।
MongoDB documents (JSON-like objects) को collections में store करता है (flexible rows की tables जैसा)। एक Mongoose schema MongoDB की flexibility के ऊपर structure और validation add करता है, तो एक Event में हमेशा right types का एक name और date होता है। हर entity (User, Event, Registration) के लिए एक clear model define करना एक organised backend की foundation है।
Practical
एक Mongoose Model
const mongoose = require('mongoose');
const eventSchema = new mongoose.Schema({
name: { type: String, required: true },
date: { type: Date, required: true },
seats: { type: Number, default: 50 },
});
// Compile the schema into a model (the 'events' collection):
const Event = mongoose.model('Event', eventSchema);
module.exports = Event;This example runs in Gri-Learn on the web, where you can edit it and see the output.
Theory
CRUD, और Controllers
Model आपको clean CRUD methods देता है, जो Promises return करते हैं (async/await इस्तेमाल कीजिए):
- Create:
Event.create({...})(याnew Event({...}).save())। - Read:
Event.find()(सब) याEvent.findById(id)(एक)। - Update:
Event.findByIdAndUpdate(id, {...})। - Delete:
Event.findByIdAndDelete(id)।
Controller वह जगह है जहाँ आप एक route के response में इन्हें call करते हैं। Controllers को इनकी अपनी files में रखना (और models को इनकी में) आपकी route definitions को thin रखता है, एक route बस कहता है 'POST /api/events, createEvent पर जाता है', और controller actual logic hold करता है। Clear separation, grow करना easy।
Practical
Model इस्तेमाल करता एक Controller (CRUD)
const Event = require('../models/event');
// create
exports.createEvent = async (req, res) => {
const event = await Event.create(req.body);
res.status(201).json(event);
};
// read all
exports.getEvents = async (req, res) => {
const events = await Event.find();
res.json(events);
};
// delete by id
exports.deleteEvent = async (req, res) => {
await Event.findByIdAndDelete(req.params.id);
res.status(204).send();
};This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
एक Mongoose-based backend में, एक Schema का role क्या है?
- यह Express server start करता है
- यह एक MongoDB collection के लिए data का shape (fields और इनके types) define करता है, और CRUD के लिए इस्तेमाल होने वाले एक Model में compile होता है
- यह CORS handle करता है
- यह एक route के same है
Show the answer
यह एक MongoDB collection के लिए data का shape (fields और इनके types) define करता है, और CRUD के लिए इस्तेमाल होने वाले एक Model में compile होता है
एक Mongoose Schema आपके data की structure define करता है, fields और इनके types (और validation), एक MongoDB collection के लिए, और आप इसे एक Model में compile करते हैं जो CRUD methods provide करता है (create, find, update, delete)। Option A wrong है: server start करना Express में app.listen है, schemas से unrelated। Option C wrong है: CORS middleware से handle होता है, एक schema से नहीं। Option D layers confuse करता है: एक route एक URL और method को एक handler से map करता है, जबकि एक schema DATA describe करता है; ये app के अलग parts में रहते हैं (routes/controllers vs models)। Schema data shape describe करता है, Model operations देता है।
Think first
MongoDB Schema-Less होने पर Mongoose Schemas क्यों Add करें?
MongoDB आपको किसी भी shape के documents store करने देता है। तो इसके ऊपर एक Mongoose schema क्यों impose करें? फिर tap कीजिए।
Show the answer
क्योंकि MongoDB की flexibility discipline के बिना powerful पर dangerous है, और एक Mongoose schema आपको STRUCTURE, VALIDATION, और CLARITY देता है benefits रखते हुए। MongoDB खुद खुशी-खुशी same collection में wildly अलग shapes के documents store कर देगा, एक event में एक name और date, दूसरे में date missing, तीसरे में 'date' एक real date की बजाय एक string की तरह stored। वह freedom जल्दी messy, inconsistent data की तरफ ले जाती है जिस पर आपका code rely नहीं कर सकता, बाद में आप जब assume करते हैं हर event का एक proper date है bugs cause करते हुए। एक Mongoose schema आपका intended shape declare करता है: name एक required String है, date एक required Date है, seats एक Number है 50 default करते हुए। अब Mongoose incoming data को उस shape के against VALIDATE करता है, उन documents को reject या flag करते हुए जो fit नहीं करते, तो आपका collection consistent रहता है और आपका code इस पर trust कर सकता है। Schema code पढ़ने वाले किसी के लिए भी data model DOCUMENT भी करता है (आप एक glance में देख सकते हैं एक Event क्या है), sensible defaults और type conversion provide करता है, और hooks और relationships जैसे features enable करता है। Crucially, आप अभी भी MongoDB के advantages रखते हैं, आप समय के साथ schema evolve कर सकते हैं, और MongoDB नीचे fast और JSON-friendly रहता है। तो Mongoose MongoDB की flexibility के ऊपर order की एक deliberate, opt-in layer है: freedom जहाँ आप चाहते हैं, guarantees जहाँ आपको चाहिए। Choice से Structure default से chaos को beat करती है।
Summary
Key takeaways
- Models (data shapes) को controllers (route logic) से separate करके backend organise कीजिए।
- Mongoose Node में MongoDB के लिए एक ODM है: एक Schema define कीजिए (fields और types), इसे एक Model में compile कीजिए।
- MongoDB collections में JSON-like documents store करता है; एक schema structure और validation add करता है।
- Model के साथ CRUD: create (create/save), read (find/findById), update (findByIdAndUpdate), delete (findByIdAndDelete); ये Promises return करते हैं (async/await इस्तेमाल कीजिए)।
- Controllers routes के response में model call करते हैं; इन्हें separate files में रखना routes को thin रखता है।
- Mongoose schemas MongoDB की flexibility के ऊपर validation और consistency add करते हैं।
- Memory hook: models data shape देते हैं, controllers logic hold करते हैं, Mongoose CRUD देता है।