« Previous Tutorial Next Tutorial »

Today we’re talking about modeling. Not the kind that involves very tall women striding down a lighted catwalk while looking angry for unexplained reasons, but the kind that involves putting together our application’s data in a structured manner.

Data models are not strictly necessary. You can build an entire app without them, and some of my previous tutorials eschew them for the slightly faster and easier approach of just directly talking to the database without defining a model for our various pieces of data. This is great for learning the basic ins and outs of talking to MongoDB. It’s very much not great for building a production-worthy app. MongoDB is very, very lenient when it comes to data structure. You can feed it something like this:

  "username": "CaptainCode",
  "fullName": "Sarah Thompson",
  "details": {
    "age": 29,
    "isAdmin": true

And then later feed it something like this:

  "username": "LordHighAdmiralFluffball",
  "fullName": "Bill Jacobs",
  "age": 25,
  "isAdmin": true

And MongoDB will be like … “OK! Sure!” and will just insert that second user into the same collection as the first, despite their structure not matching. This is problematic because it can lead to inconsistent data, which can lead to all kinds of errors in your code. Data models help ensure consistency, and they also help you track what data to send, and what data you’re going to receive, when making API calls.

Fortunately, setting up models is easy, especially since we’ll be using a nifty module called Mongoose to help with the process. Mongoose is an ORM, or Object Relational Mapping, tool, which loosely means that it’s built to take the BSON being transmitted by MongoDB and convert it to usable JavaScript objects/arrays/etc … and vice versa. This is awesome, because it makes interacting with your DB a breeze. Bonus points: it’s not hard to set up or use, at all.

So let’s get to it. First, we need to install Mongoose. Hit your terminal or command prompt, CD to your musiclist directory, and then type the following:

yarn add mongoose@5.0.4

Whew. That was a tough one, but we got through it, somehow, together, and now we’ve got mongoose installed (and Yarn automatically added it to our package.json). Now we need to tell our app to actually use Mongoose. So, open /app.js, find this line:

const bodyParser = require('body-parser');

and just below it add this line:

const mongoose = require('mongoose');

Then find this line

const app = express();

And below that, add these two:

// Connect Mongoose

That just tells Mongoose to use our local MongoDB server, and the collection “musiclist” that we created in an earlier tutorial.

Save the file, and we’re done there (for now). Let’s build our first model, the one we’ll be using for user accounts. We’re going to keep user accounts dead, stupid simple for now. No tracking people’s websites or twitter handles, no avatars, no birthdays or phone numbers. At some point we can add all of that—and maybe even two-step verification if we want to get really ambitious—but for now, we’re going with username, first name, last name, password. That’s it.

Let’s model that out. First, create a directory at the top level of your project called models – you can use mkdir for this if you want. I’m lazy and am just going to right-click in Sublime. Since this is a small application, I’m not going to bother with subdirectories here, but you totally could if you wanted. Instead, let’s just create a file called user.js. I’m going to give you all of the code here, but I strongly encourage you to type it out by hand, rather than copy-pasting. Trust me: you learn way more by doing that, especially if you mistype something and then have to fix it.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const User = new Schema({
    username: String,
    password: String,
    firstName: String,
    lastName: String

module.exports = mongoose.model('User', User);

Let’s run through those lines real quick. First we require the Mongoose module, then we map the variable Schema to mongoose’s Schema method (a schema is an object that outlines what a model should contain). We then initialize a new Schema, name it User, and tell it to contain four strings: username, password, firstName, and lastName. That bit’s important: by specifying the data type, we help prevent data corruption. We can’t accidentally pass a boolean true/false to any of these, or a numerical value, or an array. It won’t mean a thing if it ain’t got that string, so to speak.

The final line exports our model for use elsewhere. Save the file, and we’ve brought our user model in to existence. In the next tutorial, we’ll install our authentication management module, Passport, and wire it up to our user model. Stay tuned!

« Previous Tutorial Next Tutorial »