|7. MongoDB आणि Mongoose
Chapter 7Node.js & Express~1 min read

MongoDB आणि Mongoose

Real Database Connect करा

In-memory arrays production साठी नाहीत — server restart झाल्यावर data जातो. MongoDB हा NoSQL database आणि Mongoose हा Node.js साठी ODM (Object Document Mapper) आहे.

Setup

bash
npm install mongoose
# MongoDB Atlas (cloud) किंवा local MongoDB वापरा

MongoDB connect + Schema + Model

javascript
const mongoose = require('mongoose');

// Connect करा
mongoose.connect('mongodb://localhost:27017/myapp')
  .then(() => console.log('MongoDB connected!'))
  .catch(err => console.error(err));

// Schema define करा
const studentSchema = new mongoose.Schema({
  name: { type: String, required: true },
  grade: { type: String, enum: ['A', 'B', 'C', 'D'], required: true },
  email: { type: String, unique: true },
  createdAt: { type: Date, default: Date.now },
});

// Model बनवा
const Student = mongoose.model('Student', studentSchema);

module.exports = Student;

CRUD with Mongoose

javascript
// Create
const newStudent = await Student.create({ name: "Avadhoot", grade: "A" });

// Read
const all = await Student.find();
const one = await Student.findById(id);
const filtered = await Student.find({ grade: "A" });

// Update
const updated = await Student.findByIdAndUpdate(
  id,
  { grade: "A+" },
  { new: true } // updated document return करा
);

// Delete
await Student.findByIdAndDelete(id);
📌

Mongoose methods async आहेत — नेहमी async/await किंवा .then()/.catch() वापरा. Errors साठी try/catch लावा.

Key Points — लक्षात ठेवा

  • Schema — document structure define करतो
  • Model — collection शी interact करतो
  • Student.create() — नवीन document बनवा
  • Student.find() — documents मिळवा
  • findByIdAndUpdate/Delete — id ने update/delete
0/8 chapters पूर्ण