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

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more