MongoDB & Mongoose Basics
MongoDB is a popular NoSQL database that stores data as flexible JSON-like documents, pairing naturally with JavaScript and Node.js.
Mongoose is an ODM (Object Data Modeling) library that lets you define schemas and interact with MongoDB using convenient JavaScript models.
Connecting & defining a schema
Use `mongoose.connect()` to connect to a database, then `mongoose.Schema` and `mongoose.model()` to define document structure.
Basic CRUD with Mongoose
Models provide methods like `.find()`, `.create()`, `.findByIdAndUpdate()`, and `.findByIdAndDelete()` for interacting with data.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp');
const userSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model('User', userSchema);This connects to MongoDB and defines a User model with a schema.
const user = await User.create({ name: 'Ada', age: 30 });
const users = await User.find();
console.log(users.length);1create() inserts a document; find() retrieves matching documents.
Key points
- MongoDB stores flexible JSON-like documents.
- Mongoose defines schemas and models for MongoDB.
- Models provide CRUD methods like find/create/update/delete.
- Mongoose adds validation and structure on top of MongoDB's flexibility.
