Created
February 24, 2020 17:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
save is the method run by mongoose after which this pre thing triggers itself