DEV Community

Kauress
Kauress

Posted on

4

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);
  });
};

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more