Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

The first line here just imports the Mongoose module. This Mongoose package provides us
with several properties, one of which is to define the Schema. Now, the original Schema


definition here is this highlighted part:


const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const UserSchema = new Schema({
name: String,
email: String
})

const User = mongoose.model("User", UserSchema)
module.exports = User

What this does is it adds a validation to our User data model, where it says there must be


two fields in total. It will not accept either one or more than two data fields while creating a


document for a Mongoose collection. Also, it adds a validation layer to this Schema as well,


which says that the two fields, both name, and email, should be a valid string. It won't


accept an integer, Boolean, or anything other than a string for both of these fields. This is
how we define the Schema:


const mongoose = require("mongoose")
const Schema = mongoose.Schema

const UserSchema = new Schema({
name: String,
email: String
})

const User = mongoose.model("User", UserSchema)
module.exports = User

The highlighted part of this code represents the way to create a model. The first argument


of the method is our model name, which maps to the corresponding plural version of the


collection name. So, when we create a User model, this automatically maps to the user


collections in our database.

Free download pdf