Node.js ยท Chapter 25 of 43

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.

Example 1 (javascript)
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.

Example 2 (javascript)
const user = await User.create({ name: 'Ada', age: 30 });
const users = await User.find();
console.log(users.length);
Output
1

create() 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.
๐Ÿ’ก Note: MongoDB pairs naturally with Node.js since both speak JSON-like data.

๐Ÿ“ Quick Quiz

1. What kind of database is MongoDB?

2. What does Mongoose provide?

3. Which Mongoose method retrieves documents?