Search code examples
node.jsauthenticationmongoosebackendschema

Schema.prototype.pre is not a function


The .pre function of Mongoose model is not found.

// usersModel.js

const UserSchema = model(
  //name of table in db
  "UserSchema",
  new Schema({
    email: {
      type: String,
      required: [true, "Email is required"],
      unique: true,
    },
    password: {
      type: String,
      required: [true, "Password is required"],
      minlength: 8,
    },

  })
);

User.pre("save", function () { console.log("Hello from pre save")});
//or
User.pre("save", () => console.log("Hello from pre save"));

module.exports = UserSchema;
// package.json

"dependencies": {
  "cors": "^2.8.5",
  "dotenv": "^16.0.3",
  "express": "^4.18.2",
  "mongoose": "^6.8.0"
},
"engines": {
  "node": "14.x"
}

I am trying use model.pre('save', function(){}) to hash the user password, but I am getting this error:

UserSchema.pre("save", () => console.log("Hello from pre save"));
           ^
TypeError: UserSchema.pre is not a function
    at Object.<anonymous> (C:\TravelC\backend\models\usersModel.js:44:12)
   

Solution

  • I suppose it's just a typo when you write

    User.pre("save", function () { console.log("Hello from pre save")});
    

    It should be

    UserSchema.pre("save", function () { console.log("Hello from pre save")});
    

    in your actual code.

    The UserSchema that you declared is Models while Mongoose supports you to use pre middleware with Schemas instead. The logic should be defined as:

    const userSchema = new Schema(...);
    userSchema.pre('save', function() {...}) // does not use arrow function here
    const UserModel = model('UserShema', userSchema);