A
A
Alexey Shimanovich2020-11-10 02:38:18
Mongoose
Alexey Shimanovich, 2020-11-10 02:38:18

Why is a 500 error returned?

There is a router, when you try to make a POST request to it, an error 500 is returned.

I understand that the block is being processed catch, but I don’t understand why. What's my mistake?

const { Router } = require('express');
const User = require('../models/User');
const config = require('config');
const cors = require('cors');
const bodyParser = require('body-parser');

const router = Router();

const jsonParser = bodyParser.json();

const corsOptions = {
    origin: config.get('CORS.whiteList' ),
    optionsSuccessStatus: config.get('CORS.optionsSuccessStatus')
}

router.post('/login',
    cors(corsOptions),
    jsonParser,
    async(req, res) => {
        try {
            const email = req.body.email;
            console.log(email)
            const candidate = await User.findOne({ email: email });
            if (isEmpty(email)) {
                console.log(3)
                return res.status(400).json({
                    msg: 'Некоректные данные при регистрации'
                });
            }

            if (candidate) {
                return res.status(400).json({
                    msg: 'Такой email уже зарегестрирован'
                });
            }

            const user = new User({
                email
            });

            await user.create();

        } catch (err) {
            console.log(3)
            res.status(500).json({
                msg: 'Что-то пошло не так, попробуйте снова',
                err: err.stack
            });
        }

        function isEmpty(str) {
            return (!str || 0 === str.length);
        }
    }
);

module.exports = router;


As I found out, the problem is in the lines

const user = new User({
    email
});

await user.create();


For some reasonuser.create is not a function

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question