MongoDB with Mongoose basics
Mongoose gives MongoDB collections a schema and easy model methods in Node.
In this page:
Syntax
const mongoose = require('mongoose');
await mongoose.connect('mongodb://host/database');
const schema = new mongoose.Schema({ field: Type });
const Model = mongoose.model('Name', schema);
MongoDB with Mongoose basics
Mongoose defines Schemas, compiles them into Models, and connects with mongoose.connect. Models offer create, find, findById, updateOne and deleteOne. Schemas add validation and defaults on top of MongoDB's flexible documents.
Note:
Await mongoose.connect before using models.
Example: MongoDB with Mongoose basics
$ npm install mongoose
const mongoose = require("mongoose");
await mongoose.connect(process.env.MONGODB_URI);
const User = mongoose.model("User", new mongoose.Schema({ name: { type: String, required: true }, age: Number }));
await User.create({ name: "Ada", age: 36 });
console.log(await User.find({ age: { $gt: 30 } }));
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using models before connecting
- Forgetting to define required fields
- Not handling validation errors
Chapter Summary
- Schema describes fields
- Model provides queries
- connect opens the database
- Validation is built in
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: