Node.js+Express中Mongoose调用save时出现err未定义错误求助
问题排查:Mongoose save() 报错 ReferenceError: err is not defined
错误原因分析
测试代码混用回调与Promise写法,存在语法错误
user.save((err,document))多了一个右括号,正确回调参数格式应为(err, document)- 同时使用回调函数和Promise的
then/catch,但catch里的err变量未在当前作用域定义,Promise的catch接收的参数是error而非回调里的err
User模型存在两处逻辑错误
puesto字段枚举值写法错误:['empleado, gerente']是单个字符串,需拆分为两个独立字符串['empleado', 'gerente'],否则枚举验证失效- 自定义方法定义错误:
empleado.method.comparePassword应使用复数methods,否则无法通过实例调用该方法
输入数据不符合模型验证规则
- 输入的
password值为"123qwe"(长度6),但模型中password要求min:8,会触发验证失败
- 输入的
修复方案
1. 修正测试代码的save()调用(二选一)
纯Promise写法(推荐)
const User = require('./models/User'); const userInput = { nombre : "Mauricio", telefono : "12213213213", email : "mauri@gmail.com", password : "123qwe12", // 修改为符合min:8的密码 puesto : "gerente" } const user = new User(userInput); user.save() .then((document) => { console.log(document); }) .catch((error) => { console.log(error); });
纯回调写法
const User = require('./models/User'); const userInput = { nombre : "Mauricio", telefono : "12213213213", email : "mauri@gmail.com", password : "123qwe12", // 修改为符合min:8的密码 puesto : "gerente" } const user = new User(userInput); user.save((err, document) => { if (err) { console.log(err); return; } console.log(document); });
2. 修正User模型的错误
const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const empleado = new mongoose.Schema({ nombre : { type : String, required : true, min : 3, max : 20 }, telefono : { type : String, required : true, min : 8, max : 20 }, email :{ type : String, required : true, min:10, }, password : { type : String, required : true, min : 8, max : 20 }, puesto : { type : String, enum : ['empleado', 'gerente'], // 修正枚举值为两个独立字符串 required : true }, todos : [{type : mongoose.Schema.Types.ObjectId, ref: 'Todo'}] }); empleado.pre('save',function(next){ if(!this.isModified('password')) return next(); bcrypt.hash(this.password, 10,(err, passwordHash)=>{ if(err) return next(err); this.password = passwordHash; next(); }); }); // 修正为methods复数 empleado.methods.comparePassword = function(password,cb){ bcrypt.compare(password,this.password,(err,isMatch)=>{ if(err) return cb(err); if(!isMatch) return cb(null,isMatch); return cb(null,this); }); } module.exports = mongoose.model('User',empleado);
内容的提问来源于stack exchange,提问作者Mauricio Garcia
相关产品推荐
相关产品推荐

