DEV Community

Cover image for Mongoose Schema Guide
Matthew Carpenter
Matthew Carpenter

Posted on

Mongoose Schema Guide

Mongoose is an Object Data Modeler (ODM) for Node. It provides you with a simple validation and query API to help you interact with your MongoDB database. Think of mongoose as an organizer, when data comes back from the client, mongoose validates and structures your data based on your model(schema). You will always know how & what data is being stored in your database. Let's take a look at an example.

What is a Schema?

Above I mentioned structure and validation, this is your mongoose schema. Let say you have a sign up form on your page. You may not want to allow certain characters in the user name, or you may want to ensure the email address is valid when stored in your database.

This tutorial assumes you know how to use NPM or YARN to include mongoose in your project.

We first start by requiring mongoose.

//import mongoose NPM module
import mongoose from "mongoose";

// Save a reference to the Schema constructor `mongoose.model`
let Schema = mongoose.Schema;
Enter fullscreen mode Exit fullscreen mode

Above we use the schema constructor mongoose.schema and save it in a variable called Schema.

Below we create a new Schema, and name it UserSchema.

const UserSchema = new Schema({
  // `username` must be of type String
  // `username` will trim leading and trailing whitespace before it's saved
  // `username` is a required field and throws a custom error message if not supplied
  username: {
    type: String,
    trim: true,
    required: "Username is Required"
  },
  // `password` must be of type String
  // `password` will trim leading and trailing whitespace before it's saved
  // `password` is a required field and throws a custom error message if not supplied
  // `password` uses a custom validation function to only accept values 6 characters or more
  password: {
    type: String,
    trim: true,
    required: "Password is Required",
    validate: [
      function(input) {
        return input.length >= 6;
      },
      "Password should be longer."
    ]
  },
  // `email` must be of type String
  // `email` must be unique
  // `email` must match the regex pattern below and throws a custom error message if it does not
  email: {
    type: String,
    unique: true,
    match: [/.+@.+\..+/, "Please enter a valid e-mail address"]
  }
});
Enter fullscreen mode Exit fullscreen mode

Above, we are telling our Schema how to validate and store our data. We are basically saying i'm expecting the following information to come back. Your username has to be a string, it will trim all whitespace before and after your string, or throw an error if you try to submit blank.

Create your model & Export

// This creates our model from the above schema, using mongoose's model method
let User = mongoose.model("User", UserSchema);

// Export the User model
module.exports = User;
Enter fullscreen mode Exit fullscreen mode

Use the model

alt text

So, you have created a simple login on the front end, and a post route on the backend to store the data in our mongoDB via mongoose. Take a look below at our post route. We create a new instance of User and pass in req.body. We create a new document in our database and send user back to the client or an error if the information is not valid.

const User = require("./userModel.js");

app.post("/submit", function(req, res) {
         /*req.body {
             username: "mongod", 
             password: "pass123", 
             email: "none@none.com"
            } 
  Create a new user using req.body (this data came from the client)*/
  let user = new User(req.body);

  User.create(user)
    .then(function(dbUser) {
      // If saved successfully, send the the new User document to the client
      res.json(dbUser);
    })
    .catch(function(err) {
      // If an error occurs, send the error to the client
      res.json(err);
    });
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Ta-Da, we just created a mongoose schema and used it to validated the data being stored in our mongoDB. This is a great tool to use when building a mongoDB, you have complete control over what goes in and how its being stored when it gets there. Thanks for reading!

Top comments (4)

Collapse
 
ajnasz profile image
Lajos Koszti

Trim the email rather than the password =]

Collapse
 
angus profile image
Angus Lam • Edited

Cool intro to schemas! I’ve been revisiting Mongoose recently and still not really sure if there’s a need to name the schema objects, since the only places I would pass them to are their respective model objects. Any thoughts on creating the schema directly inside mongoose.model’s second argument?

Collapse
 
veronicorn profile image
Veronica

This is great, Matt! :)

Collapse
 
mcarpenter profile image
Matthew Carpenter

Thanks Veronica!