使用Mongoose model.pre('save')时遇错误:TypeError: UserSchema.pre is not a function
解决Mongoose中
.pre方法报错:TypeError: xxx.pre is not a function 你的代码核心问题是混淆了Schema与Model的创建顺序,并且错误地对Model对象调用了Schema专属的方法。model()函数返回的是Mongoose模型对象,而.pre()是Schema实例的方法,不能直接在模型上调用,同时代码里还出现了未定义的User变量,这也是报错原因之一。
修正后的完整代码
// usersModel.js const { Schema, model } = require('mongoose'); // 确保正确解构Schema和model // 1. 先创建Schema实例 const UserSchema = new Schema({ email: { type: String, required: [true, "Email is required"], unique: true, }, password: { type: String, required: [true, "Password is required"], minlength: 8, }, }); // 2. 在Schema实例上调用.pre()添加保存前中间件 // 注意:不要用箭头函数,否则无法通过this访问当前文档实例 UserSchema.pre("save", function (next) { console.log("Hello from pre save"); // 这里可以添加密码哈希逻辑,示例: // const bcrypt = require('bcrypt'); // bcrypt.hash(this.password, 10, (err, hash) => { // if (err) return next(err); // this.password = hash; // next(); // }); next(); // 必须调用next(),否则保存流程会阻塞 }); // 3. 基于Schema创建Model(第一个参数是MongoDB集合名称,Mongoose会自动转为复数形式) const User = model("User", UserSchema); module.exports = User;
关键注意事项
- 严格遵循「创建Schema → 绑定Schema中间件 → 创建Model」的顺序
- 不要用箭头函数作为
pre的回调,箭头函数没有独立的this,无法访问当前要保存的文档实例 - 中间件内部必须调用
next(),才能让Mongoose继续执行后续的保存流程
内容的提问来源于stack exchange,提问作者John Vasile
相关产品推荐
相关产品推荐

