ReferenceError: 在我尝试使用Node.js和Express在MongoDB中插入文档时,err未定义

huangapple go评论55阅读模式
英文:

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);
    });

huangapple
  • 本文由 发表于 2023年5月15日 10:20:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定