Easily Develop Node.js and MongoDB Apps with Mongoose

Chris Sevilleja
👁️ 610,304 views
💬 comments

Node.js and MongoDB are a pair made for each other. Being able to use JSON across the board and JavaScript makes development very easy. This is why you get popular stacks like the MEAN stack that uses Node, Express (a Node.js framework), MongoDB, and AngularJS.

CRUD is something that is necessary in most every application out there. We have to create, read, update, and delete information all the time.

Today we'll be looking at code samples to handle CRUD operations in a Node.js, ExpressJS, and MongoDB application. We'll use the popular Node package, mongoose.

Table of Contents

    These code samples were used to create a Node.js RESTful API since you are performing CRUD functions when creating an API. Read through that tutorial to see these commands in action. This article will be more of a reference for the various commands and their usage.

    What Is Mongoose?

    mongoose is an object modeling package for Node that essentially works like an ORM that you would see in other languages (like Eloquent for Laravel).

    Mongoose allows us to have access to the MongoDB commands for CRUD simply and easily. To use mongoose, make sure that you add it to you Node project by using the following command:

    $ npm install mongoose --save

    Now that we have the package, we just have to grab it in our project:

    var mongoose = require('mongoose');

    We also have to connect to a MongoDB database (either local or hosted):

    mongoose.connect('mongodb://localhost/myappdatabase');

    Let's get to the commands.

    Defining a Model

    Before we can handle CRUD operations, we will need a mongoose Model. These models are constructors that we define. They represent documents which can be saved and retrieved from our database.

    Mongoose Schema The mongoose Schema is what is used to define attributes for our documents.

    Mongoose Methods Methods can also be defined on a mongoose schema. These are methods

    Sample Model for Users

    // grab the things we need
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    // create a schema
    var userSchema = new Schema({
      name: String,
      username: { type: String, required: true, unique: true },
      password: { type: String, required: true },
      admin: Boolean,
      location: String,
      meta: {
        age: Number,
        website: String
      },
      created_at: Date,
      updated_at: Date
    });
    
    // the schema is useless so far
    // we need to create a model using it
    var User = mongoose.model('User', userSchema);
    
    // make this available to our users in our Node applications
    module.exports = User;

    This is how a Schema is defined. We must grab mongoose and mongoose.Schema. Then we can define our attributes on our userSchema for all the things we need for our user profiles. Also notice how we can define nested objects as in the meta attribute.

    The allowed SchemaTypes are:

    • String
    • Number
    • Date
    • Buffer
    • Boolean
    • Mixed
    • ObjectId
    • Array

    We will then create the mongoose Model by calling mongoose.model. We can also do more with this like creating specific methods. This is a good place to create a method to hash a password.

    Custom Method

    // grab the things we need
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    // create a schema
    var userSchema ...
    
    // custom method to add string to end of name
    // you can create more important methods like name validations or formatting
    // you can also do queries and find similar users 
    userSchema.methods.dudify = function() {
      // add some stuff to the users name
      this.name = this.name + '-dude'; 
    
      return this.name;
    };
    
    // the schema is useless so far
    // we need to create a model using it
    var User = mongoose.model('User', userSchema);
    
    // make this available to our users in our Node applications
    module.exports = User;

    Sample Usage

    Now we have a custom model and method that we can call in our code:

    // if our user.js file is at app/models/user.js
    var User = require('./app/models/user');
    
    // create a new user called chris
    var chris = new User({
      name: 'Chris',
      username: 'sevilayha',
      password: 'password' 
    });
    
    // call the custom method. this will just add -dude to his name
    // user will now be Chris-dude
    chris.dudify(function(err, name) {
      if (err) throw err;
    
      console.log('Your new name is ' + name);
    });
    
    // call the built-in save method to save to the database
    chris.save(function(err) {
      if (err) throw err;
    
      console.log('User saved successfully!');
    });

    This is a very useless custom method, but the idea for how to create a custom method and use it stands. We can use this for making sure that passwords are hashed before saving, having a method to compare passwords, find users with similar attributes, and more.

    Run a Function Before Saving

    We also want to have a created_at variable to know when the record was created. We can use the Schema pre method to have operations happen before an object is saved.

    Here is the code to add to our Schema to have the date added to created_at if this is the first save, and to updated_at on every save:

    // on every save, add the date
    userSchema.pre('save', function(next) {
      // get the current date
      var currentDate = new Date();
    
      // change the updated_at field to current date
      this.updated_at = currentDate;
    
      // if created_at doesn't exist, add to that field
      if (!this.created_at)
        this.created_at = currentDate;
    
      next();
    });

    Now on every save, we will add our dates. This is also a great place to hash passwords to be sure that we never save plaintext passwords.

    We can also define more things on our models and schemas like statics and indexes. Be sure to take a look at the mongoose docs for more information.

    Create

    We'll be using the User method we created earlier. The built-in save method on mongoose Models is what is used to create a user:

    // grab the user model
    var User = require('./app/models/user');
    
    // create a new user
    var newUser = User({
      name: 'Peter Quill',
      username: 'starlord55',
      password: 'password',
      admin: true
    });
    
    // save the user
    newUser.save(function(err) {
      if (err) throw err;
    
      console.log('User created!');
    });

    Read

    There are many reasons for us to query our database of users. We'll need one specific user, all users, similar users, and many more scenarios. Here are a few examples:

    Find All

    // get all the users
    User.find({}, function(err, users) {
      if (err) throw err;
    
      // object of all the users
      console.log(users);
    });

    Find One

    // get the user starlord55
    User.find({ username: 'starlord55' }, function(err, user) {
      if (err) throw err;
    
      // object of the user
      console.log(user);
    });

    Find By ID

    // get a user with ID of 1
    User.findById(1, function(err, user) {
      if (err) throw err;
    
      // show the one user
      console.log(user);
    });

    Querying

    You can also use MongoDB query syntax.

    // get any admin that was created in the past month
    
    // get the date 1 month ago
    var monthAgo = new Date();
    monthAgo.setMonth(monthAgo.getMonth() - 1);
    
    User.find({ admin: true }).where('created_at').gt(monthAgo).exec(function(err, users) {
      if (err) throw err;
    
      // show the admins in the past month
      console.log(users);
    });

    Update

    Here we will find a specific user, change some attributes, and then re-save them.

    Get a User, Then Update

    // get a user with ID of 1
    User.findById(1, function(err, user) {
      if (err) throw err;
    
      // change the users location
      user.location = 'uk';
    
      // save the user
      user.save(function(err) {
        if (err) throw err;
    
        console.log('User successfully updated!');
      });
    
    });

    Remember that since we created the function to change the updated_at date, this will also happen on save.

    Find and Update

    An even easier method to use since we dont have to grab the user, modify, and then save. We are just issuing a mongodb findAndModify command.

    // find the user starlord55
    // update him to starlord 88
    User.findOneAndUpdate({ username: 'starlord55' }, { username: 'starlord88' }, function(err, user) {
      if (err) throw err;
    
      // we have the updated user returned to us
      console.log(user);
    });

    Find By ID and Update

    // find the user with id 4
    // update username to starlord 88
    User.findByIdAndUpdate(4, { username: 'starlord88' }, function(err, user) {
      if (err) throw err;
    
      // we have the updated user returned to us
      console.log(user);
    });

    Delete

    Get a User, Then Remove

    // get the user starlord55
    User.find({ username: 'starlord55' }, function(err, user) {
      if (err) throw err;
    
      // delete him
      user.remove(function(err) {
        if (err) throw err;
    
        console.log('User successfully deleted!');
      });
    });

    Find and Remove

    // find the user with id 4
    User.findOneAndRemove({ username: 'starlord55' }, function(err) {
      if (err) throw err;
    
      // we have deleted the user
      console.log('User deleted!');
    });

    Find By ID and Remove

    // find the user with id 4
    User.findByIdAndRemove(4, function(err) {
      if (err) throw err;
    
      // we have deleted the user
      console.log('User deleted!');
    });

    Conclusion

    Hopefully this will act as a good reference guide when using the mongoose package in Node.js and MongoDB applications.

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.