Sequelize doesn't find data with getter()

Viewed 86

My query is always coming empty, when I try to use the where with the age of the user (this one obtained with getter(), from Sequelize).

Model:

const { DataTypes, Model } = require('sequelize');
const bcrypt = require('bcryptjs');

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

class User extends Model {
    static init(sequelize) {
        super.init({
            name: DataTypes.STRING,
            address: DataTypes.STRING,
            cpf: DataTypes.STRING,
            city: DataTypes.STRING,
            uf: DataTypes.STRING,
            birthday: DataTypes.DATE,
            age: {
                type: DataTypes.INTEGER,
                get() {
                    const rawValue = getAge(this.getDataValue('birthday'));
                    return rawValue
                    //console.log('Age', this.getDataValue('age'));
                },

            },
            genre: DataTypes.ENUM(['Feminino', 'Masculino']),
            phone: DataTypes.STRING,
            password: DataTypes.STRING,
            password_hash: DataTypes.VIRTUAL,
            role: DataTypes.ENUM(['Admin', 'User']),
            active: DataTypes.BOOLEAN
        },
            {
                sequelize
            }
        );
        //Antes de salvar, cria a senha_hash para salvar no banco de dados.
        this.addHook('beforeSave', async (user) => {
            if (user.password) {
                user.password = await bcrypt.hash(user.password, 8);
            }
        });
        return this;
    }

    verifyPassword(pass, hash) {
        //Compara a senha que o usuário enviou com a senha já cadastrada no BD
        return bcrypt.compare(pass, hash)
    }
}

module.exports = User;

When I do the search without the age condition, it returns all the data, including the correct age.

How can I get a user by age?

Note: In my table, the age field is NULL.

0 Answers
Related