• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 2/21/22

Create a Data Schema

One of the advantages of using Mongoose to manage your MongoDB database is that you can implement strict data schemas to make an app more robust. Let's start by creating a Thing schema for every  Thing  put up for sale on our app.

Create a Thing Schema

Let's look at how to create a thing schema in the next video!

Inside your  backend  folder, create a new folder called  models , and within that new folder, a file called  thing.js  :

const mongoose = require('mongoose');

const thingSchema = mongoose.Schema({
  title: { type: String, required: true },
  description: { type: String, required: true },
  imageUrl: { type: String, required: true },
  userId: { type: String, required: true },
  price: { type: Number, required: true },
});

module.exports = mongoose.model('Thing', thingSchema);

What this does is:

  • Create a data schema that contains the fields for each  Thing  , their type, and whether or not they are a required field.

  • Export that schema as a Mongoose model, making it available for your Express app.

This model allows you to enforce your data structure and makes read and write operations to the database far simpler, as you will see in the next chapters.

Let's Recap!

  • Mongoose's  Schema  method lets you create a data schema for your MongoDB database.

  • The  model  method turns that schema into a usable model.

Now that you are all set with the data schema, let's see how to save and retrieve data from the database!

Example of certificate of achievement
Example of certificate of achievement