Mongoose Schema Guide
Tags: node, beginners, javascript
Published: 2018-11-08 13:22:42

---
title: Mongoose Schema Guide
published: true
description: Quick guide to setup Mongoose Schema
tags: #nodeJS, #beginner, #javascript
cover_image: https://media.cuinsight.com/wp-content/uploads/2017/04/bigstock-Server-racks-in-server-room-da-150954236.jpg
---
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.

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

// Save a reference to the Schema constructor `mongoose.model`
let Schema = mongoose.Schema;
```
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`. 

```javascript
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"]
  }
});
```
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
```javascript
// 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;
```

###Use the model
![alt text](https://thepracticaldev.s3.amazonaws.com/i/kbcu3i8tuqf18v6hwwe4.png "Simple login screen")

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.

```javascript
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);
    });
});
```


###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!