Tutorial

Easily Develop Node.js and MongoDB Apps with Mongoose

Draft updated on Invalid Date
author

Chris on Code

Easily Develop Node.js and MongoDB Apps with Mongoose

This tutorial is out of date and no longer maintained.

Introduction

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 for almost 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.

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 your Node project by using the following command:

  1. npm install mongoose --save

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

  1. var mongoose = require('mongoose');

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

  1. 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 that 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.greet = function() {
      // add some stuff to the users name
      this.name = 'Hello ' + this.name;

      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: 'chris',
      password: 'password'
    });

    // call the custom method.
    // this will greet the user.
    chris.greet(function(err, name) {
      if (err) throw err;

      console.log(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: 'Test',
      username: 'test',
      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 test
    User.find({ username: 'test' }, 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 don’t have to grab the user, modify, and then save. We are just issuing a MongoDB findAndModify command.

    // find the user test
    // update them to test2
    User.findOneAndUpdate({ username: 'test' }, { username: 'test2' }, function(err, user) {
      if (err) throw err;

      // we have the updated user returned to us
      console.log(user);
    });

### Find By ID and Update

```javascript
    // find the user with id 4
    // update username to test4
    User.findByIdAndUpdate(4, { username: 'test4' }, 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 test
    User.find({ username: 'test' }, function(err, user) {
      if (err) throw err;

      // delete the user
      user.remove(function(err) {
        if (err) throw err;

        console.log('User successfully deleted!');
      });
    });

Find and Remove

    // find the user with username test
    User.findOneAndRemove({ username: 'test' }, 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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Chris on Code

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel