Mongoose basics
Mongoose is a library that adds schemas, validation and helper methods on top of the MongoDB driver.
In this page:
Syntax
const mongoose = require('mongoose');
await mongoose.connect(connectionString);
const Model = mongoose.model('Name', new mongoose.Schema({ field: Type }));
await Model.create({ field: value });
Mongoose basics
Install mongoose, connect with mongoose.connect, define a Schema and compile a Model. Documents created from the model are validated against the schema and gain methods such as save and populate.
Mongoose is popular for structured applications and integrates well with Express.
Note:
Mongoose queues operations until it connects, but you should still await connect.
Example: Mongoose basics
const mongoose = require("mongoose");
await mongoose.connect(process.env.MONGODB_URI);
const userSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model("User", userSchema);
const ada = await User.create({ name: "Ada", age: 36 });
console.log(ada.name, ada._id instanceof mongoose.Types.ObjectId); // Ada true
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using models before connecting
- Forgetting await
- Expecting Mongoose to be schemaless
Chapter Summary
- mongoose.connect opens the connection
- Schema plus Model
- Validation and defaults built in
- Adds save and populate
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: