We use schemas and models to organize and control how data is saved and used in a database. It helps keep data clean and easy to work with.
0
0
Defining schemas and models in Express
Introduction
When you want to save user information like names and emails in a database.
When you need to keep track of products in an online store with details like price and description.
When you want to make sure data follows certain rules before saving it.
When you want to easily find, update, or delete data in your app.
Syntax
Express
const mongoose = require('mongoose'); const schemaName = new mongoose.Schema({ field1: { type: String, required: true }, field2: String // more fields }); const ModelName = mongoose.model('ModelName', schemaName);
A schema defines the shape and rules for your data.
A model is a tool to work with that data in the database.
Examples
This example creates a user schema with name, email, and age fields. Name and email are required.
Express
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
age: Number
});
const User = mongoose.model('User', userSchema);This example defines a product with title, price (required), and inStock status.
Express
const productSchema = new mongoose.Schema({
title: String,
price: { type: Number, required: true },
inStock: Boolean
});
const Product = mongoose.model('Product', productSchema);Sample Program
This program connects to a MongoDB database, defines a book schema and model, saves a new book, then finds and prints it.
Express
const mongoose = require('mongoose'); async function run() { await mongoose.connect('mongodb://localhost:27017/testdb'); const bookSchema = new mongoose.Schema({ title: { type: String, required: true }, author: String, pages: Number }); const Book = mongoose.model('Book', bookSchema); const newBook = new Book({ title: 'Learn Express', author: 'Jane Doe', pages: 150 }); await newBook.save(); const foundBook = await Book.findOne({ title: 'Learn Express' }); console.log(foundBook); await mongoose.connection.close(); } run();
OutputSuccess
Important Notes
Always close the database connection when done to avoid issues.
Use required: true to make sure important data is always provided.
Models let you easily add, find, update, or delete data in your app.
Summary
Schemas define how your data looks and what rules it follows.
Models let you work with that data in the database.
Using schemas and models helps keep your app's data organized and reliable.