英文:
ReferenceError: err is not defined when I try to insert a document with mongoose in mongodb with nodejs and express
问题
I'm trying to insert a document in my mongo database but when I use .save
function and err
parameter it says that err is not defined.
这是我尝试将文档插入到我的Mongo数据库中,但当我使用.save
函数和err
参数时,它显示err未定义。
英文:
I'm trying to insert a document in my mongo database but when I use .save
function and err
parameter it says that err is not defined
this is my model
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();
});
});
empleado.method.comparePassword = function(password,cb){
bcrypt.compare(password,this.password,(err,isMatch)=>{
if(err)
return cb(err);
else{
if(!isMatch)
return cb(null,isMatch);
return cb(null,this);
}
});
}
module.exports = mongoose.model('User',empleado);
This is what i tried
const User = require('./models/User');
const userInput = {
nombre : "Mauricio",
telefono : "12213213213",
email : "mauri@gmail.com",
password : "123qwe",
puesto : "gerente"
}
const user = new User(userInput);
user.save((err,document))
.then(()=>{
console.log(document);
}).catch(()=>{
console.log(err);
});
答案1
得分: 0
err
is defined in the catch
callback:
user.save()
.then(() => {
console.log(user);
}).catch((err) => {
console.log(err);
});
英文:
err
is defined in the catch
callback:
user.save()
.then(()=>{
console.log(user);
}).catch((err)=>{
console.log(err);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论