Connecting to MongoDB with Mongoose
Connecting to MongoDB with Mongoose
MongoDB stores documents as JSON-like objects, and Mongoose adds schemas and modeling on top of the Node driver. This combination is a common choice for Express APIs.
Installing and connecting
npm install mongoose
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/shop');
connect takes a connection string naming the database. The driver manages the connection pool in the background.
Defining a schema
A schema describes the shape of a document:
const itemSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, default: 0 },
tags: [String],
});
const Item = mongoose.model('Item', itemSchema);
The model works like a collection handle. Mongoose pluralizes the name into the MongoDB collection automatically.
CRUD in practice
// Create
const item = await Item.create({ name: 'Keyboard', price: 79 });
// Read
const all = await Item.find();
const one = await Item.findById(item._id);
// Update
await Item.findByIdAndUpdate(item._id, { price: 69 });
// Delete
await Item.findByIdAndDelete(item._id);
Validation lives in the schema
required, min, max, and custom validators run on save. Enforce rules inside the schema so bad data never reaches the database regardless of which route sends it.
Queries are promises
Model methods return promises, so they pair with await inside async route handlers. Existing Express code that used an array for items can swap the array calls for these database calls without changing the response shape.
Key Points
- Mongoose models documents on top of MongoDB.
- connect names the server and database.
- Schemas declare fields, types, and validation.
- Model methods wrap create, read, update, delete.
- Queries are promises you can await in routes.