×
By the end of this chapter, you should be able to:
schema
and model
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 document structure for a collection. Even though mongo is "schemaless", mongoose allows us to overlay a schema at the application level which can define document attributes, validation of data, class and instance methods, and even associations.
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 mongoose
To get started with mongoose
, let's require it and connect to our database. This can go in our main app.js
file for now:
app.js.
const mongoose = require("mongoose"); mongoose.set("debug", true); // this will log the mongo queries to the terminal mongoose.Promise = global.Promise; // let's use ES2015 promises for mongoose! No callbacks necessary! // connect to the DB mongoose .connect("mongodb://localhost/first_mongoose_app", { useMongoClient: true // this option is necessary for Mongoose 4.11 and up }) .then(() => { // once connected, give a success message console.log("Connected to MongoDB"); }) .catch(err => { // if something goes wrong let us know console.log(err); });
Note: You can also put this in models/index
if you like.
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 a folder called models
.
// create our schema which describes what each document will look like const instructorSchema = new mongoose.Schema( { firstName: String, lastName: String, isHilarious: { type: Boolean, default: true }, favoriteColors: [String] }, { timestamps: true } // automatically adds createdAt and updatedAt ); /* create our model from the schema to perform CRUD actions on our documents (which are objects created from the model constructor) */ const 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 a models/index.js
file for easy exports:
// let's export out an object and attach to it a property called Instructor exports.Instructor = require("./instructor");
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.
You can see how a basic folder structure and model would look like here.
When you're ready, move on to CRUD with Mongoose