Home > OS >  How next() works here?
How next() works here?

Time:02-05

i just do password encryption before saving it in db, i just want to know how next() works here? i know that next() helps us to jump one middleware to next middleware.

userModel.js

....
....
//below will encrypt password before saving user in db
//password is the field of  documents og mongodb

userSchema.pre("save", async function () {
  console.log(this.password);

  if (!this.isModified("password")) {
    next();
  }

  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
});
....
....

//full code userModel.js

const mongoose=require("mongoose");
const bcrypt=require("bcryptjs");

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique:true },
  password: { type: String, required: true },
  pic: {
    type: String,
    default:
      "https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
  },
},
{
    timestamps:true,
});


//below compare given password with before password
userSchema.methods.matchPassword=async function(enteredPassword){
console.log("this.password",this.password)
return await bcrypt.compare(enteredPassword,this.password)
}


//below will encrypt password before saving user in db
userSchema.pre("save", async function () {
  console.log(this.password);

  if (!this.isModified("password")) {
    next();
  }

  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
});

//mongoose.model(<Collectionname>, <CollectionSchema>)
//generally const "User" and  "User" in mongoose.model() written in same name
const User=new mongoose.model("User",userSchema);

module.exports=User;

I am new in node js please help me to understand middleware

CodePudding user response:

You can see more about middleware in mongoose here:

How mongoose middleware works and what is next()?

In short, next() will tell mongoose you are done and to continue with the next step in the execution chain. In your example, it will execute the "save" command to save the password to database if the password is not modified and go to next callback (if has).

  • Related