Teaching Newbies since 2014

kauress

  • Home
  • Javascript ❤
    • JavaScript
    • Node.js
  • WebDev Tuts
  • screencasts
  • Resources
  • VR & AR
  • Contact
  • Github
  • Twitter
  • YouTube
  • RSS
  • C++
You are here: Home / Apps / Sweet & Sour mongoose.js methods – 1

September 8, 2019 by: Kauress

Sweet & Sour mongoose.js methods – 1

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

Plug-n-Play authentication is officially out now!
Sweet & Sour mongoose.js methods – 2

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2021 ·Kauress