• 10 heures
  • Moyenne

Ce cours est visible gratuitement en ligne.



J'ai tout compris !

Mis à jour le 21/02/2022

Create a Data Schema

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

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!

Exemple de certificat de réussite
Exemple de certificat de réussite