排序Model.prototype。(customFunction)不起作用

时间:2018-07-17 13:23:58

标签: javascript node.js express sequelize.js

我正在尝试在Sequelize模型中定义一个customFunction。 但我收到一个错误:

  

TypeError:user.getJWT不是函数       在User.create.then(/projects/test/a/app/controllers/UserController.js:22:29)

这是models/user.js的代码:

module.exports = function(sequelize, Sequelize) {
    var User = sequelize.define('User', {
        id: {
          type: Sequelize.INTEGER(11),
          allowNull: true,
          primaryKey: true,
          autoIncrement: true
        },
        user_id: {
          type: Sequelize.STRING(255),
          allowNull: true,
          defaultValue: ''
        }
      });

      User.prototype.getJWT = function() {
        let expiration_time = parseInt(CONFIG.jwt_expiration);
        return "Bearer " + jwt.sign({
          user_id: this.user_id,
          role: this.role
        }, CONFIG.jwt_encryption, {
          expiresIn: expiration_time
        });
      }
      return User
    }

这就是我在控制器中调用此原型函数的方式...

User.create(body).then((user) => {
      user.token = user.getJWT(); // and here I get the error ..TypeError: user.getJWT is not a function 
      res.json(user);
    }

我也尝试过使用User.Instance.prototype.getJWT,但这甚至无法正常工作,因为我正在使用sequelize 4.x.x版

这是user对象的日志:

{ [Function: User]
  sequelize:
   Sequelize {
     options:
      { dialect: 'mysql',
        dialectModulePath: null,
        host: 'localhost',
        protocol: 'tcp',
        define: [Object],
        query: {},
        sync: {},
        timezone: '+00:00',
        logging: [Function: bound consoleCall],
        omitNull: false,
        native: false,
        replication: false,
        ssl: undefined,
        pool: {},
        quoteIdentifiers: true,
        hooks: {},
        retry: [Object],
        transactionType: 'DEFERRED',
        isolationLevel: null,
        databaseVersion: '5.6.0',
        typeValidation: false,
        benchmark: false,
        operatorsAliases: false,
        port: '3306' },
     config:
      { database: 'mlmapi',
        username: 'root',
        password: 'a5f7c674',
        host: 'localhost',
        port: '3306',
        pool: {},
        protocol: 'tcp',
        native: false,
        ssl: undefined,
        replication: false,
        dialectModulePath: null,
        keepDefaultTimezone: undefined,
        dialectOptions: undefined },
     dialect:
      MysqlDialect {
        sequelize: [Circular],
        connectionManager: [Object],
        QueryGenerator: [Object] },
     queryInterface: QueryInterface { sequelize: [Circular], QueryGenerator: [Object] },
     models:
      { Company: [Object],
        Dashboard: [Object],
        User: [Circular],
        UserCompany: [Object] },
     modelManager: ModelManager { models: [Array], sequelize: [Circular] },
     connectionManager:
      ConnectionManager {
        sequelize: [Circular],
        config: [Object],
        dialect: [Object],
        versionPromise: null,
        dialectName: 'mysql',
        pool: [Object],
        lib: [Object] },
     importCache:
      { '/projects/test/code/models/company.model.js': [Object],
        '/projects/test/code/models/dashboard.js': [Object],
        '/projects/test/code/models/user.model.js': [Circular] },
     test:
      { _trackRunningQueries: false,
        _runningQueries: 0,
        trackRunningQueries: [Function: trackRunningQueries],
        verifyNoRunningQueries: [Function: verifyNoRunningQueries] } },
  options:
   { timestamps: false,
     validate: {},
     freezeTableName: false,
     underscored: false,
     underscoredAll: false,
     paranoid: false,
     rejectOnEmpty: false,
     whereCollection: { id: 3 },
     schema: null,
     schemaDelimiter: '',
     defaultScope: {},
     scopes: [],
     indexes: [],
     name: { plural: 'Users', singular: 'User' },
     omitNull: false,
     tableName: 'user',
     sequelize:
      Sequelize {
        options: [Object],
        config: [Object],
        dialect: [Object],
        queryInterface: [Object],
        models: [Object],
        modelManager: [Object],
        connectionManager: [Object],
        importCache: [Object],
        test: [Object] },
     hooks:
      { beforeUpdate: [Array],
        beforeCreate: [Array],
        beforeSave: [Array] },
     uniqueKeys: {} },
  associations: {},
  underscored: undefined,
  tableName: 'user',
  _schema: null,
  _schemaDelimiter: '',
  rawAttributes:
   { id:
      { type: [Object],
        allowNull: true,
        primaryKey: true,
        autoIncrement: true,
        Model: [Circular],
        fieldName: 'id',
        _modelAttribute: true,
        field: 'id' },
     name:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'name',
        _modelAttribute: true,
        field: 'name' },
     user_id:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'user_id',
        _modelAttribute: true,
        field: 'user_id' },
     role:
      { type: [Object],
        allowNull: true,
        defaultValue: 'user',
        Model: [Circular],
        fieldName: 'role',
        _modelAttribute: true,
        field: 'role' },
     email:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'email',
        _modelAttribute: true,
        field: 'email' },
     password:
      { type: [Object],
        allowNull: true,
        Model: [Circular],
        fieldName: 'password',
        _modelAttribute: true,
        field: 'password' },
     position:
      { type: [Object],
        allowNull: true,
        Model: [Circular],
        fieldName: 'position',
        _modelAttribute: true,
        field: 'position' },
     sponsor:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'sponsor',
        _modelAttribute: true,
        field: 'sponsor' },
     master_sponsor:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'master_sponsor',
        _modelAttribute: true,
        field: 'master_sponsor' },
     master_key:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'master_key',
        _modelAttribute: true,
        field: 'master_key' },
     packageAmount:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'packageAmount',
        _modelAttribute: true,
        field: 'packageAmount' },
     status:
      { type: [Object],
        allowNull: true,
        defaultValue: '1',
        Model: [Circular],
        fieldName: 'status',
        _modelAttribute: true,
        field: 'status' },
     main_id:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'main_id',
        _modelAttribute: true,
        field: 'main_id' },
     upline:
      { type: [Object],
        allowNull: true,
        defaultValue: '{level:}',
        Model: [Circular],
        fieldName: 'upline',
        _modelAttribute: true,
        field: 'upline' } },
  primaryKeys:
   { id:
      { type: [Object],
        allowNull: true,
        primaryKey: true,
        autoIncrement: true,
        Model: [Circular],
        fieldName: 'id',
        _modelAttribute: true,
        field: 'id' } },
  _timestampAttributes: {},
  _readOnlyAttributes: [],
  _hasReadOnlyAttributes: 0,
  _isReadOnlyAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _dataTypeChanges: {},
  _dataTypeSanitizers: {},
  _booleanAttributes: [],
  _dateAttributes: [],
  _hstoreAttributes: [],
  _rangeAttributes: [],
  _jsonAttributes: [],
  _geometryAttributes: [],
  _virtualAttributes: [],
  _defaultValues:
   { name: [Function: wrapper],
     user_id: [Function: wrapper],
     role: [Function: wrapper],
     email: [Function: wrapper],
     sponsor: [Function: wrapper],
     master_sponsor: [Function: wrapper],
     master_key: [Function: wrapper],
     packageAmount: [Function: wrapper],
     status: [Function: wrapper],
     main_id: [Function: wrapper],
     upline: [Function: wrapper] },
  fieldRawAttributesMap:
   { id:
      { type: [Object],
        allowNull: true,
        primaryKey: true,
        autoIncrement: true,
        Model: [Circular],
        fieldName: 'id',
        _modelAttribute: true,
        field: 'id' },
     name:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'name',
        _modelAttribute: true,
        field: 'name' },
     user_id:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'user_id',
        _modelAttribute: true,
        field: 'user_id' },
     role:
      { type: [Object],
        allowNull: true,
        defaultValue: 'user',
        Model: [Circular],
        fieldName: 'role',
        _modelAttribute: true,
        field: 'role' },
     email:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'email',
        _modelAttribute: true,
        field: 'email' },
     password:
      { type: [Object],
        allowNull: true,
        Model: [Circular],
        fieldName: 'password',
        _modelAttribute: true,
        field: 'password' },
     position:
      { type: [Object],
        allowNull: true,
        Model: [Circular],
        fieldName: 'position',
        _modelAttribute: true,
        field: 'position' },
     sponsor:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'sponsor',
        _modelAttribute: true,
        field: 'sponsor' },
     master_sponsor:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'master_sponsor',
        _modelAttribute: true,
        field: 'master_sponsor' },
     master_key:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'master_key',
        _modelAttribute: true,
        field: 'master_key' },
     packageAmount:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'packageAmount',
        _modelAttribute: true,
        field: 'packageAmount' },
     status:
      { type: [Object],
        allowNull: true,
        defaultValue: '1',
        Model: [Circular],
        fieldName: 'status',
        _modelAttribute: true,
        field: 'status' },
     main_id:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'main_id',
        _modelAttribute: true,
        field: 'main_id' },
     upline:
      { type: [Object],
        allowNull: true,
        defaultValue: '{level:}',
        Model: [Circular],
        fieldName: 'upline',
        _modelAttribute: true,
        field: 'upline' } },
  fieldAttributeMap: {},
  uniqueKeys: {},
  _hasBooleanAttributes: false,
  _isBooleanAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _hasDateAttributes: false,
  _isDateAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _hasHstoreAttributes: false,
  _isHstoreAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _hasRangeAttributes: false,
  _isRangeAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _hasJsonAttributes: false,
  _isJsonAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _hasVirtualAttributes: false,
  _isVirtualAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _hasGeometryAttributes: false,
  _isGeometryAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  _hasDefaultValues: true,
  attributes:
   { id:
      { type: [Object],
        allowNull: true,
        primaryKey: true,
        autoIncrement: true,
        Model: [Circular],
        fieldName: 'id',
        _modelAttribute: true,
        field: 'id' },
     ....
     .....
     upline:
      { type: [Object],
        allowNull: true,
        defaultValue: '{level:}',
        Model: [Circular],
        fieldName: 'upline',
        _modelAttribute: true,
        field: 'upline' } },
  tableAttributes:
   { id:
      { type: [Object],
        allowNull: true,
        primaryKey: true,
        autoIncrement: true,
        Model: [Circular],
        fieldName: 'id',
        _modelAttribute: true,
        field: 'id' },
     name:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'name',
        _modelAttribute: true,
        field: 'name' },
     user_id:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'user_id',
        _modelAttribute: true,
        field: 'user_id' },
     role:
      { type: [Object],
        allowNull: true,
        defaultValue: 'user',
        Model: [Circular],
        fieldName: 'role',
        _modelAttribute: true,
        field: 'role' },
     email:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'email',
        _modelAttribute: true,
        field: 'email' },
     password:
      { type: [Object],
        allowNull: true,
        Model: [Circular],
        fieldName: 'password',
        _modelAttribute: true,
        field: 'password' },
     position:
      { type: [Object],
        allowNull: true,
        Model: [Circular],
        fieldName: 'position',
        _modelAttribute: true,
        field: 'position' },
     sponsor:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'sponsor',
        _modelAttribute: true,
        field: 'sponsor' },
     master_sponsor:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'master_sponsor',
        _modelAttribute: true,
        field: 'master_sponsor' },
     master_key:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'master_key',
        _modelAttribute: true,
        field: 'master_key' },
     packageAmount:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'packageAmount',
        _modelAttribute: true,
        field: 'packageAmount' },
     status:
      { type: [Object],
        allowNull: true,
        defaultValue: '1',
        Model: [Circular],
        fieldName: 'status',
        _modelAttribute: true,
        field: 'status' },
     main_id:
      { type: [Object],
        allowNull: true,
        defaultValue: '',
        Model: [Circular],
        fieldName: 'main_id',
        _modelAttribute: true,
        field: 'main_id' },
     upline:
      { type: [Object],
        allowNull: true,
        defaultValue: '{level:}',
        Model: [Circular],
        fieldName: 'upline',
        _modelAttribute: true,
        field: 'upline' } },
  primaryKeyAttributes: [ 'id' ],
  primaryKeyAttribute: 'id',
  primaryKeyField: 'id',
  _hasPrimaryKeys: true,
  _isPrimaryKey: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
  autoIncrementAttribute: 'id',
  _scope: {},
  _scopeNames: [ 'defaultScope' ] }

2 个答案:

答案 0 :(得分:4)

您的函数“定义”未正确关闭。根据{{​​3}}文档,以下方法应该起作用。

module.exports = function(sequelize, Sequelize) {
    var User = sequelize.define('User', {
        id: {
          type: Sequelize.INTEGER(11),
          allowNull: true,
          primaryKey: true,
          autoIncrement: true
        },
        user_id: {
          type: Sequelize.STRING(255),
          allowNull: true,
          defaultValue: ''
        }
      }); // you missed a closing parenthesis here

      User.prototype.getJWT = function() {
        let expiration_time = parseInt(CONFIG.jwt_expiration);
        return "Bearer " + jwt.sign({
          user_id: this.user_id,
          role: this.role
        }, CONFIG.jwt_encryption, {
          expiresIn: expiration_time
        });
      }
      return User
    }

看到user对象的日志,它看起来不像User模型的正确实例(而是模型本身)。您能显示控制器本身,特别是在您需要模型的需求阶段吗?您可以尝试这样的控制器吗?

User.create(body).then((user) => {
    user.token = user.getJWT(); // and here I get the error ..TypeError: user.getJWT is not a function 
    res.json(user);
}

这不应正确输出用户:s

答案 1 :(得分:0)

您是否尝试过像这样使用它:

    module.exports = function (sequelize, Sequelize) {
        // ... model

        User.getJWT = function () {
            let expiration_time = parseInt(CONFIG.jwt_expiration);
            return "Bearer " + jwt.sign({
                user_id: this.user_id,
                role: this.role
            }, CONFIG.jwt_encryption, {
                    expiresIn: expiration_time
                });
        }
        return User
    }

您正在指定instance level method,并且您正在尝试使用类级别的方法。 (请选中模型扩展部分)