Javascript 续集模型。原型。(自定义功能)不工作

Javascript 续集模型。原型。(自定义功能)不工作,javascript,node.js,express,sequelize.js,Javascript,Node.js,Express,Sequelize.js,我试图在Sequelize模型中定义一个自定义函数。 但我有一个错误: 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',

我试图在
Sequelize
模型中定义一个自定义函数。 但我有一个错误:

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

以下是
用户
对象的日志:

{ [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' ] }

函数“define”未正确关闭。根据文件规定,以下各项应有效

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.create(body).then((user) => {
    user.token = user.getJWT(); // and here I get the error ..TypeError: user.getJWT is not a function 
    res.json(user);
}

这不应正确输出用户:您的函数“define”未正确关闭。根据文件规定,以下各项应有效

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.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

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

    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
    }

您正在指定,并且正在尝试使用类级方法。(查看型号扩展部分)

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

    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
    }

您正在指定,并且正在尝试使用类级方法。(检查型号扩展部分)

请回答,我会给你发送一些BTC请回答,我会给你发送一些BTC在我的配置中进行了测试,工作正常。您使用什么版本的node和sequelize?这可能来自这里好的,谢谢。您是否尝试记录用户对象?它会生成什么类型的日志?您拥有的日志看起来像一个模型定义,而不是这个模型的实例。您是否记录了用户或用户?(大写u?)。您应该看到用户对象的值。如果删除user.token=user.getJWT();从您的控制器,它是否正确输出用户?你能给我看看控制器吗?(需要模型和用户?@RameshPareek如果你能展示你的控制器,我认为它来自模型的导入方式!因此,如果删除行“user.token=user.getJWT();”,您的api返回了您的用户?刚刚在我的配置中进行了测试,工作正常。您使用什么版本的node和sequelize?这可能来自这里好的,谢谢。您是否尝试记录用户对象?它会生成什么类型的日志?您拥有的日志看起来像一个模型定义,而不是这个模型的实例。您是否记录了用户或用户?(大写u?)。您应该看到用户对象的值。如果删除user.token=user.getJWT();从您的控制器,它是否正确输出用户?你能给我看看控制器吗?(需要模型和用户?@RameshPareek如果你能展示你的控制器,我认为它来自模型的导入方式!因此,如果删除行“user.token=user.getJWT();”,您的用户是否由api返回?