DEV Community

Cover image for Sweet & Sour mongoose.js methods
Kauress
Kauress

Posted on

Sweet & Sour mongoose.js methods

Alt Text

I’ve been using Mongoose (ODM library for MongoDB) quite a bit for the authentication project. NoSQL databases like MongoDB do seem more flexible for web apps which depend quite a bit on user interaction. Example a user might decide to login with a social media account or register with their email, a password and secret question-answer.

I find it way easier to write a mongoose method that deal with updating app.js, user.js, routes.js every time a user decides to do something a bit different!

Here is a short mongoose.js method which is a pre-save hook. It will check if a username exists in your schema. If the username exsists it will return an error, if not then the method will facilitate the saving of the username to the db: The method is essentially a function unto your user schema.

UserSchema.pre("save", function(next) {
    const self = this;
    User.find({
        name: self.name
    }, function(err, docs) {
        if (!docs.length) {
            next();
        } else {
            console.log("user exists: ", self.name);
            next(new Error("User exists!"));
        }
    });
});

ps: I'll keep editing this document & add in more functions

Discussion (1)