DEV Community

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

Posted on

2 1

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay