0
0
Expressframework~30 mins

Defining schemas and models in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Defining Schemas and Models in Express with Mongoose
📖 Scenario: You are building a simple Express app to manage a list of books in a library. Each book has a title, author, and number of pages.
🎯 Goal: Create a Mongoose schema and model for the books collection to store book details in MongoDB.
📋 What You'll Learn
Create a Mongoose schema named bookSchema with fields title, author, and pages
Add a model named Book using the bookSchema
Use correct Mongoose types: String for title and author, Number for pages
Export the Book model
💡 Why This Matters
🌍 Real World
Defining schemas and models is essential for structuring data in MongoDB when building backend applications with Express and Mongoose.
💼 Career
Backend developers often create schemas and models to ensure data consistency and to interact with databases efficiently.
Progress0 / 4 steps
1
Set up Mongoose import and connection
Write the code to import mongoose and connect to a MongoDB database at mongodb://localhost:27017/library.
Express
Need a hint?

Use require('mongoose') to import mongoose. Use mongoose.connect() with the given URL.

2
Create the bookSchema with fields
Create a Mongoose schema called bookSchema with fields: title and author as String, and pages as Number.
Express
Need a hint?

Use new mongoose.Schema({ ... }) and define each field with its type.

3
Create the Book model from bookSchema
Create a Mongoose model named Book using mongoose.model with the schema bookSchema.
Express
Need a hint?

Use mongoose.model('Book', bookSchema) to create the model.

4
Export the Book model
Export the Book model using module.exports.
Express
Need a hint?

Use module.exports = Book to export the model for use in other files.