首页 > 解决方案 > 续集:“TypeError:无法将未定义或空值转换为对象”

问题描述

我正在尝试注册新用户,但返回错误“TypeError:无法将未定义或 null 转换为对象”。我知道这里有一些关于它的帖子,但我不能,也许是因为花了很多时间专注和疲惫。很抱歉为此创建另一个帖子。

数据库.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 && model.associate(this.connection.models));
    }
}

export default new Database();

用户存储库.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])(?=.*[!@#\$%\^&\*])(?=.{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:\Projetos\Real\github-project\backend\node_modules\sequelize\lib\model.js:1692:47)
    at Function.findOne (D:\Projetos\Real\github-project\backend\node_modules\sequelize\lib\model.js:1917:23)
    at store (D:\Projetos\Real\github-project\backend\src\app\repositories\UserRepository.js:35:53)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

标签: node.jssequelize.js

解决方案


推荐阅读