← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 2 of 7

Mongoose basics

Mongoose is a library that adds schemas, validation and helper methods on top of the MongoDB driver.

In this page:

  1. Mongoose basics
Syntax
javascript
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

javascript
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
  1. Using models before connecting
  2. Forgetting await
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.