Making a Schema

How to build a Schema with Mongoose

A schema is a way of defining data to be put into a database. With MongoDB, since the values are stored in a document form, we need to tell it how to store its data, and what types of data to store.

To get started, create a directory in your source folder and name it schemas

Inside of the schemas folder, you can create a new file and call it whatever you like. It is recommended you name it based on what kind of information it stores, so it is easy to locate in the future.

Inside of the file you just created, you need to require Schema and model from mongoose, so:

const { Schema, model } = require("mongoose");

Now you can define the Schema.

If you find yourself stuck, feel free to read the mongoose documentation, as it has all of the syntax you will need.

To do this, we need to use the Schema class.

In this tutorial, we will store a few basic entries into our database, but they won't really do much.

const schema = new Schema({
  userId: {
    type: String,
    required: true,
  },
  enabled: {
    type: Boolean,
    default: false,
  },
  level: {
    type: Number,
    default: 0,
  },
});

Now, this will store 3 values, userId, enabled?, and level. These values don't have any meaning but are just here for the guide.

Finally, we need to export our Schema so we can use it in the future. It needs to be exported as a model, which is perfectly okay since Mongoose has this built-in to the package.

module.exports = model("Schema", schema);

The first value of model() is the name of your Schema, or whatever you want it to be stored as in MongoDB.

The second value is the schema. So in this case, it is just called "schema".

Completely finished, our schema file should look like this:

const { Schema, model } = require("mongoose");

const schema = new Schema({
  userId: {
    type: String,
    required: true,
  },
  enabled: {
    type: Boolean,
    default: false,
  },
  level: {
    type: Number,
    default: 0,
  },
});

module.exports = model("Schema", schema);

This Schema can be required in other files, and you will learn about that in the Database Manipulation page.

Last updated