← Back to Node.js Course | Chapter 9: Database Integration | Lesson 2 of 7

MongoDB with Mongoose basics

Mongoose gives MongoDB collections a schema and easy model methods in Node.
Syntax
javascript
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

bash
$ 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
  1. Using models before connecting
  2. Forgetting to define required fields
  3. 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:

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.