Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Created February 24, 2020 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heytulsiprasad/1ef4432a7b90d1432b8457a95b62c595 to your computer and use it in GitHub Desktop.
Save heytulsiprasad/1ef4432a7b90d1432b8457a95b62c595 to your computer and use it in GitHub Desktop.
some mongoose pre handler to run before a query takes place with mongoDB
const bcrypt = require("bcryptjs")
const mongoose = require("mongoose")
// we need to design a schema first of all
const userSchema = new mongoose.Schema({
name: {
type: String
},
password: {
type: String
},
email: {
type: String
}
})
userSchema.pre(
"save",
async function(next) {
const user = this;
// this happens before saving a document
if (user.isModified("password")) {
user.password = await bcrypt.hash(user.password, 8);
}
next();
}
)
const User = mongoose.model("User", userSchema);
module.exports = User;
@heytulsiprasad
Copy link
Author

save is the method run by mongoose after which this pre thing triggers itself

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment