0
0
Expressframework~5 mins

Defining models in Express

Choose your learning style9 modes available
Introduction

Models help you organize and manage your data in an Express app. They act like blueprints for how data should look and behave.

When you want to store user information like names and emails.
When you need to save blog posts or articles with titles and content.
When you want to keep track of products in an online store.
When you need to validate data before saving it to a database.
When you want to easily update or retrieve data in a structured way.
Syntax
Express
const mongoose = require('mongoose');

const ModelNameSchema = new mongoose.Schema({
  fieldName: { type: DataType, required: true },
  anotherField: DataType
});

const ModelName = mongoose.model('ModelName', ModelNameSchema);

module.exports = ModelName;

Use mongoose.Schema to define the shape of your data.

mongoose.model creates a model you can use to work with the data.

Examples
This defines a User model with required name and email fields.
Express
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true }
});

const User = mongoose.model('User', userSchema);
This defines a Product model with title and price fields, both optional.
Express
const productSchema = new mongoose.Schema({
  title: String,
  price: Number
});

const Product = mongoose.model('Product', productSchema);
Sample Program

This Express app connects to MongoDB, defines a User model, and provides routes to add and list users.

Express
const express = require('express');
const mongoose = require('mongoose');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true });

// Define a simple User model
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true }
});
const User = mongoose.model('User', userSchema);

const app = express();
app.use(express.json());

// Route to create a new user
app.post('/users', async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).send(user);
  } catch (error) {
    res.status(400).send(error.message);
  }
});

// Route to get all users
app.get('/users', async (req, res) => {
  const users = await User.find();
  res.send(users);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Make sure MongoDB is running before starting your app.

Models help keep your data organized and consistent.

Use required: true to make sure important fields are filled.

Summary

Models define how your data looks and behaves in Express apps.

Use Mongoose schemas and models to create and manage data easily.

Models help validate data and connect your app to a database.