MongoDB with Mongoose
Mongoose is an object data modelling (ODM) library for MongoDB and Node.js. It lets you define schemas with types and validation, then work with models that create, query and update documents.
Defining a Schema and Model
The schema describes fields, types and rules. timestamps adds createdAt and updatedAt automatically.
// npm install mongoose
import mongoose from 'mongoose'
await mongoose.connect(process.env.MONGODB_URI)
const productSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true },
category: { type: String, enum: ['Grains', 'Beverages', 'Oils', 'Snacks', 'Sweeteners'] },
price: { type: Number, min: 0, required: true },
stock: { type: Number, default: 0 },
}, { timestamps: true })
const Product = mongoose.model('Product', productSchema)
console.log(Product.collection.name)products
Creating Documents and Validation
create() validates before saving. Invalid data throws a ValidationError.
const p = await Product.create({ name: 'Walnuts', category: 'Snacks', price: 17 })
console.log(p.stock, p.createdAt instanceof Date)
try {
await Product.create({ name: 'Bad', price: -1 })
} catch (err) {
console.log(err.name, '-', err.errors.price.message)
}0 true ValidationError - Path `price` (-1) is less than minimum allowed value (0).
Querying
Model methods mirror the driver. lean() returns plain objects, which is faster for read-only use.
const snacks = await Product.find({ category: 'Snacks' })
.select('name price -_id')
.sort({ price: 1 })
.lean()
console.log(snacks)[
{ name: 'Dark Chocolate', price: 4.25 },
{ name: 'Almonds', price: 15 },
{ name: 'Walnuts', price: 17 }
]References and populate()
Use ref to link models; populate() replaces the id with the referenced document.
const Order = mongoose.model('Order', new mongoose.Schema({
product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
qty: Number,
}))
const walnuts = await Product.findOne({ name: 'Walnuts' })
await Order.create({ product: walnuts._id, qty: 3 })
const order = await Order.findOne().populate('product', 'name price')
console.log(order.product.name, order.qty)Walnuts 3
Frequently asked questions
What is the difference between Mongoose and MongoDB?
MongoDB is the database. Mongoose is a Node.js library on top of the MongoDB driver that adds schemas, validation, middleware and helpers like populate.
Why does Mongoose pluralise my collection name?
By default the model name is lowercased and pluralised (Product → products). Pass a third argument to mongoose.model or the collection schema option to set it yourself.
When should I use lean() in Mongoose?
Use lean() for read-only queries such as API responses. It skips building full Mongoose documents and is noticeably faster.