ChibiNya
ChibiNya

Reputation: 133

Sequelize Query returning strange models

When I make a query using sequelize, such as this

let User  = require('../models').User;
...
User.findOne({ where:{ email :  email }}).then( user => {
    console.log(user);
})

The user object returned there looks very strange and has some negative side effects. It looks like this (linking because too long):

https://pastebin.com/HLVHVetN

So I can't do things like user.email or user.instanceMethod as many examples show. Even worse, when I attempt to call an instance method, this references the function, not the model.

What am I doing wrong?

EDIT: Here is how my User model looks

'use strict';
let Sequelize = require('sequelize');
let bcrypt = require('bcrypt');

module.exports = (sequelize, DataTypes) => {


let User = sequelize.define('User', {
    email: {
        type: Sequelize.STRING(100), allowNull: true, unique: true,
        validate: {
            isEmail: {
                msg: 'No es una dirección de correo electrónico.'
            },
        }
    },
    google_id: {type: Sequelize.STRING(100)},

    facebook_id: {type: Sequelize.STRING(100)},
    password_digest: {
        type: Sequelize.STRING,
    },
    password: {
        type: Sequelize.VIRTUAL,
        allowNull: true,
        validate: {
            len: [6, Infinity]
        }
    },
    password_confirmation: {
        type: Sequelize.VIRTUAL
    },

    token_reset: {type: Sequelize.STRING(100)},
    token_confirm: {type: Sequelize.STRING(100)},
    browser_key: {type: Sequelize.STRING(100)},
    registry_ip: {type: Sequelize.STRING(60)},
    registry_date: {type: Sequelize.DATE, defaultValue: Sequelize.NOW},
    account_confirmed: {type: Sequelize.BOOLEAN, defaultValue: false},
    terms_accepted: {type: Sequelize.BOOLEAN, allowNull: false}, 
    account_active: {type: Sequelize.BOOLEAN, defaultValue: true},
    current_ip: {type: Sequelize.STRING(60)},
    login_date: {type: Sequelize.DATE, defaultValue: Sequelize.NOW}
}, {
    freezeTableName: true,
    indexes: [{unique: true, fields: ['email']}],
    instanceMethods: {
        authenticate: function (value) {
            console.log("THIS",this);
            console.log("comparing passwords",value, this.password_digest);
            if (bcrypt.compareSync(value, this.password_digest))
                return this;
            else
                return false;
        }
    }
});`

Upvotes: 0

Views: 241

Answers (1)

owais
owais

Reputation: 4922

Inside sequelize promise you will get properties from dataValues. so if you want to access in same thenable promise use User.dataValues.email and definately this will point to sequelize object you need to return the values and use in other function if you don't want to use that promise. other way around is to use raw:true

User.findOne({raw:true,  where:{ email :  email }}).then( user => {
    console.log(user);
})

Upvotes: 1

Related Questions