Экспресс / Пн goose Бросить новую Ошибка не передается - PullRequest
0 голосов
/ 17 апреля 2020

У меня 1 проблема, связанная с mon goose при использовании почтальона для проверки моего apis.

  1. Ни throw new Error() из userSchema не возвращается к ошибке route.post catch .

Как мне получить либо throw new Error() для возврата в скрипт router.post?

Скрипт работает правильно, когда адрес электронной почты и пароль соответствуют тому, что находится в базе данных.

Если я console.log(no email) или no password с оператором перспективы if(), они запускаются, но сообщение throw new Error() не делает это относится к оператору catch на router.post . Если я console.log (ошибка) на router.post Я получаю

Ошибка: электронная почта не найдена в Function.userSchema.statics.validatePassword (C: \ Users \ Samson \ Documents \ JS \ nodeProjects \ task-manager \ src \ models \ users. js: 60: 15) в processTicksAndRejected (внутренний / process / task_queues. js: 97: 5) в asyn c C: \ Users \ Samson \ Documents \ JS \ nodeProjects \ task-manager \ src \ routers \ user. js: 66: 22 * ​​1038 *

Но почтальону передается {}

Ниже я приведу код и снимки экрана как пользовательской модели, схемы и route.post

Объект схемы

    userSchema.statics.validatePassword = async function (email, password) {
    const user = this;
    const userObj = await user.findOne({
        "email": email
    });

    if (!userObj) {
        console.log("no email")
        throw new Error("No email found ");
    }

    const answer = await bcrypt.compare(password, userObj.password);

    if (!answer) {
        console.log("no password")
        throw new Error('Incorrect Password');
    }

    return answer;

}


Пн goose Пользовательский модель

    const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true,
        lowercase: true,
        validate(name) {
            if (name.length <= 0) {
                throw new Error("Please fill in a name");
            }
        }

    },
    age: {
        type: Number,
        required: true,
        validate(age) {
            if (age < 18) {
                throw new Error('Participates must be 18 years of age or older');
            }
        }
    },
    email: {
        type: String,
        required: true,
        lowercase: true,
        trim: true,
        unique: true,
        validate(address) {
            if (!validator.isEmail(address)) {
                throw new Error('Please enter a valid email address');
            }
        }
    },
    password: {
        type: String,
        required: true,
        trim: true,
        validate(secret) {
            if (secret.length <= 6 || secret.includes('password')) {
                throw new Error("Please select a password longer than 6 characters and that doesn't include the term password");
            }
        }
    }
});


router.post

    router.post('/users/login', async (req, res) => {

    try {
        const user = await User.validatePassword(req.body.email, req.body.password);
        res.status(200).send("user and password validated " + user);
    } catch (error) {
        console.log(error)
        res.status(400).send(error);
    }
});


enter image description here

1 Ответ

0 голосов
/ 18 апреля 2020
userSchema.statics.validatePassword = async function (email, password) {
const user = this;
const userObj = await user.findOne({
    "email": email
});

if (!userObj) {
    return 0
}

const answer = await bcrypt.compare(password, userObj.password);

if (!answer) {
    return -1;
}

return answer;
}

router.post

router.post('/users/login', async (req, res) => {

try {
    const user = await User.validatePassword(req.body.email, req.body.password);
if(user == 0){
    return res.status(404).send('no email found')
}
if(user == -1){
    return res.status(404).send('Incorrect Password')
}
    res.status(200).send("user and password validated " + user);
} catch (error) {
    console.log(error)
    res.status(400).send(error);
}
});
...