Sequelize Query返回奇怪的模型

时间:2018-05-25 19:57:02

标签: node.js sequelize.js

当我使用sequelize进行查询时,例如

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

返回的用户对象看起来很奇怪并且有一些负面的副作用。它看起来像这样(链接因为太长):

https://pastebin.com/HLVHVetN

所以我不能像许多例子那样做user.email或user.instanceMethod之类的事情。更糟糕的是,当我尝试调用实例方法时,this引用函数,而不是模型。

我做错了什么?

编辑:这是我的用户模型的外观

'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;
        }
    }
});`

1 个答案:

答案 0 :(得分:1)

在sequelize承诺中,您将从dataValues获取属性。所以,如果你想访问相同的可用承诺使用 User.dataValues.email 而且肯定会指向续集对象 如果您不想使用该承诺,则需要返回值并在其他函数中使用。 另一种方法是使用raw:true

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