DEV Community

Kauress
Kauress

Posted on

Sweet & Sour mongoose.js methods – 2

Mongoose.js

This is part of the 'Sweet & Sour mongoose.js methods' series.
In this function we will write a method that acts upon the UserSchema to check whether an email OR username already exists in the database. As an example use-case, this method can then be used in the any of your routes files by exporting the "User" to check whether an email address already exists in the database during the registration process.

Schema statics methods act directly upon the user. In this case the method is called "emailCheck". As you might know methods are functions that act upon an object and in this case the UserSchema. The function takes in an email address and callback as arguments. For any particular User The findOne method is used to match the email passed as an as argument to "emailCheck" with an email address in the database. So out here {email:email} is a query condition. The database will not be queried unless it is executed with "exec".


UserSchema.statics.emailCheck = function(email, callback) {
  User.findOne({ email: email }).exec(function(error, user) {
    if (error) {
      return callback(error);
    }
    // Pass user to callback and handle whether email exist in the callback.
    callback(null, user);
  });
};

Top comments (0)