Sequelize: «Ошибка типа: не удается преобразовать неопределенный или нулевой в объект»

#node.js #sequelize.js

#node.js #sequelize.js

Вопрос:

Я пытаюсь зарегистрировать нового пользователя, но возвращаю ошибку «Ошибка типа: не удается преобразовать неопределенный или нулевой в объект». Я знаю, что здесь есть несколько сообщений об этом, но я не могу, возможно, из-за того, что трачу много времени на сосредоточение и усталость. Извините, что создал еще один пост для этого.

database.js

 import Sequelize from 'sequelize';

import User from '../app/models/User';

import databaseConfig from '../config/database';

const models = [
    User,
];

class Database {
    constructor(){
        this.init();
    }

    init() {
        this.connection = new Sequelize(databaseConfig);

        models
            .map(model => model.init(this.connection))
            .map(model => model.associate amp;amp; model.associate(this.connection.models));
    }
}

export default new Database();
  

UserRepository.js

     import *  as Yup from 'yup';
    const { v4: uuid } = require('uuid');
    
    import User from '../models/User';
    
    class UserRepository {
        async store(req, res) {
            try {
                //Checks if the fields have been filled correctly
                const schema = Yup.object().shape({
                    name: Yup.string()
                        .required('Este campo é obrigatório.'),
                    bio: Yup.string()
                        .required('Este campo é obrigatório.'),
                    email: Yup.string()
                        .email()
                        .required('Este campo é obrigatório.'),
                    user: Yup.string()
                        .required('Este campo é obrigatório.'),
                    password: Yup.string()
                        .required('Este campo é obrigatório.')
                        .matches(
                            /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^amp;*])(?=.{8,})/,
                            'Sua senha deve conter pelo menos uma letra maiúscula, uma letra minúscula, um número e um caractere especial.'
                        )
                });
    
                //Checks if the befored password have all characters of the rule
                if(!(await schema.isValid(req.body))) {
                    return res.status(400).json({ error: 'A validação falhou.' });
                }
    
                //Checks if the email already exists
                //const userExists = await User.findOne({ where: { email: req.body.email } || { user: req.body.user }});
                const userExists = await User.findOne({ where: { email: req.body.email }});
                if(userExists) {
                    return res.status(400).json({error: 'Esse email já está cadastrado.'});
                }
    
                //Abstraction of fields
                const { name, bio, email, user, password } = req.body;
    
                const data = {
                    id: uuid(),
                    name,
                    bio,
                    email,
                    user,
                    password,
                    account_type: 'free_account'
                }
    
                await User.create(data);
    
                //If everything is correct, the information will be registered and returned.
                return res.json(data);
            } catch (error) {
                //console.log(req.body);
                res.status(400).json(`Erro: ${error}.`);
                console.log(error);
            }
        }

}

export default new UserRepository();
  

Модель: User.js

 import Sequelize, { Model } from 'sequelize';
import bcrypt from 'bcryptjs';

class User extends Model {
    static init(sequelize) {
        // Fields registered by the user
        super.init(
            {
                id: Sequelize.STRING,
                name: Sequelize.STRING,
                bio: Sequelize.STRING,
                email: Sequelize.STRING,
                user: Sequelize.STRING,
                password: Sequelize.VIRTUAL,
                password_hash: Sequelize.STRING,
                accountType: Sequelize.STRING,
            },
            {
                sequelize,
                paranoid: true
            },
        );

        // Hashes the password before save
        this.addHook('beforeSave', async user => {
            if (user.password) {
                user.password_hash = await bcrypt.hash(user.password, 8);
            }
        });

        return this;
    }

    /*
        Checks whether the password is correct before the user signs in.
        *As it is just a password check, and not necessarily a business rule, I left it in the model.*
    */
    checkPassword(password) {
        return bcrypt.compare(password, this.password_hash);
    }
}

export default User;
  

Ошибка консоли:

 TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Function.findAll (D:ProjetosRealgithub-projectbackendnode_modulessequelizelibmodel.js:1692:47)
    at Function.findOne (D:ProjetosRealgithub-projectbackendnode_modulessequelizelibmodel.js:1917:23)
    at store (D:ProjetosRealgithub-projectbackendsrcapprepositoriesUserRepository.js:35:53)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
  

Комментарии:

1. Вы проверили req.body.email ?