{ Introduction to Mongoose. }

Objectives:

By the end of this chapter, you should be able to:

  • Compare and contrast Mongo and Mongoose
  • Define essential terms like schema and model
  • Connect to a Mongo database using Mongoose

Mongoose Intro

So far we have seen how to connect to a database with mongo and perform CRUD and query operations on a mongo collection. While we can connect mongo with our node applications, there is a useful tool called mongoose, which gives us access to additional methods to help with querying and building larger applications.

Mongoose also introduces two concepts which we will examine:

schema - a schema is a structure for a collection. Even though mongo is "schemaless", mongoose allows us to create a structure for our collection and add validations, class methods, instance methods and associates (which we will examine later).
model - a model is an object which is created from the schema and it contains methods for creating, finding, updating and deleting documents.

Let's get started. Create a project directory, and inside of it run the following commands.

touch app.js
npm init -y
npm install --save mongoose

To get started with mongoose, let's require it and connect to our database. We will be placing all of our models inside of a folder called models, so let's create a file called index.js and write the following code inside of it.

var mongoose = require('mongoose');
mongoose.set('debug',true); // this will log the mongo queries to the terminal
mongoose.connect('mongodb://localhost/first_mongoose_app'); // connect to the DB

mongoose.Promise = global.Promise // let's use ES2015 promises for mongoose! No callbacks necessary!

Schema

Now let's add our first Schema. You can read more about the different data types here. For now, let's create a file called instructor.js and place the following inside of the models folder.

// create our schema which describes what each document will look like
var instructorSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    isHilarious: {type: Boolean, default: true},
    favoriteColors: [String],
    createdAt: { type: Date, default: Date.now }
});

// create our model from the schema to perform CRUD actions on our documents (which are objects created from the model constructor)
var Instructor = mongoose.model('Instructor', instructorSchema);

// Now it would be nice if we could aggregate our models into one single file and export them out to be used in our routes and other files, so let's export this model out to another file!

module.exports = Instructor;

Now let's add to our models/index.js file

var mongoose = require('mongoose');
mongoose.set('debug',true); // this will log the mongo queries to the terminal
mongoose.connect('mongodb://localhost/first_mongoose_app'); // connect to the DB

mongoose.Promise = global.Promise // let's use ES2015 promises for mongoose! No callbacks necessary!

// let's export out an object and attach to it a property called Instructor
module.exports.Instructor = require('./instructor') // the value of this property will be the Instructor model that we exported out in our instructor.js file!

We will be using this index.js file in our routes files so it's important to isolate our model logic from our routing (or controller) logic.

Sample App

You can see how a basic folder structure and model would look like here.

When you're ready, move on to Mongoose CRUD

Continue