2017-04-17 77 views
0

尝试在模型中定义一个函数,以便我可以拥有一组通用函数。这里是我的代码表。我正在使用续集ORM和nodejs在mySql中使用sequelize定义静态函数(如mongoose)

"use strict"; 

module.exports = function(sequelize, DataTypes) { 
    var AttendantUser = sequelize.define('AttendantUser', { 
    user_id : { 
     type : DataTypes.CHAR(36), 
     defaultValue : DataTypes.UUIDV4, 
     primaryKey : true 
    }, 
    mobile : { 
     type : DataTypes.BIGINT, 
     allowNull : false, 
     unique : true 
    }, 
    reset_code : { 
     type : DataTypes.INTEGER, 
     allowNull : true, 
     defaultValue : '0000' 
    } 
    },{ 
    freezeTableName : true, 
    paranoid : true 
    }); 


AttendantUser.usernameInUse = function (callback) { 
console.log("fefe"); 
callback(null, "hello"); 
} 
    return AttendantUser; 
}; 

当我尝试使用usernameInUse函数时出现的错误是。 错误:mModels.usernameInUse不是函数

+0

你检出了钩子吗? http://docs.sequelizejs.com/en/v3/docs/hooks/ –

+0

什么是“mModels”变量? – piotrbienias

回答

1

这就是classMethods的用途。在Sequelize documentation page处查找选项“[options.classMethods]”。

这是你的代码必须是什么样子:

"use strict"; 

module.exports = function(sequelize, DataTypes) { 
    var AttendantUser = sequelize.define('AttendantUser', { 
    user_id : { 
     type : DataTypes.CHAR(36), 
     defaultValue : DataTypes.UUIDV4, 
     primaryKey : true 
    }, 
    mobile : { 
     type : DataTypes.BIGINT, 
     allowNull : false, 
     unique : true 
    }, 
    reset_code : { 
     type : DataTypes.INTEGER, 
     allowNull : true, 
     defaultValue : '0000' 
    } 
    },{ 
    freezeTableName : true, 
    paranoid : true, 
    classMethods : { 
     usernameInUse = function (callback) { 
      console.log("fefe"); 
      callback(null, "hello"); 
      return this; 
     } 
    } 
    }); 

与数据库同步,您可以导入与

AttendantUser = require('/path/to/attendant-user'); 

模型然后可以调用静态方法,像这样:

AttendantUser.usernameInUse(() => {console.log('callback called.');})