Javascript 如何扩展所有Sequelize模型?
我添加了几个Sequelize扩展方法db-ext.js:Javascript 如何扩展所有Sequelize模型?,javascript,object,sequelize.js,extend,Javascript,Object,Sequelize.js,Extend,我添加了几个Sequelize扩展方法db-ext.js: module.exports={ findResult:(过滤器,列='id')=>{ filter.raw=true; 返回this.findOne(过滤器)。然后(行=>{ 如果(!行)返回null; 返回行[col]| | null; }) }, ... }; 然后,在models/index.js中,我想将这些方法添加到所有模型中: 。。。 让后遗症; if(配置环境使用环境变量){ sequelize=新的sequelize
module.exports={
findResult:(过滤器,列='id')=>{
filter.raw=true;
返回this.findOne(过滤器)。然后(行=>{
如果(!行)返回null;
返回行[col]| | null;
})
},
...
};
然后,在models/index.js中,我想将这些方法添加到所有模型中:
。。。
让后遗症;
if(配置环境使用环境变量){
sequelize=新的sequelize(process.env[configEnv.use\u env\u variable],configEnv);
}否则{
sequelize=新的sequelize(configEnv.database、configEnv.username、configEnv.password、configEnv);
}
财政司司长
.readdirSync(\uuuDirName)
.filter(文件=>{
返回(file.indexOf('.')!==0)&&(file!==basename)&&(file.slice(-3)==='.js');
})
.forEach(文件=>{
const model=sequelize['import'](path.join(_dirname,file));
//-----托多:这个坏了。在这里或任何地方怎么办?
Object.keys(dbExt.forEach)(项=>{
模型[项目]=dbExt[项目];
})
db[model.name]=模型;
});
...
启动节点时,输出错误:
您触发了未处理的退出,您可能忘记捕获拒绝承诺:
TypeError:this.findOne不是函数
在
我希望我能说清楚。非常感谢您的帮助 实现您想要的目标的正确方法是使用DAOS 为任何模型创建dao类。模型A的类方法将是您对由模型A表示的表A所做的查询。每个类将使用您希望派生类继承的方法显式扩展一个基本dao类 例如
class BaseDao {
constructor(model) {
this.model = model
}
create(data) {
return this.model.create(data);
}
findAll(options) {
return this.model.findAll(options);
}
myGreatMethod() {
// Do whatever you need
}
}
现在:
class ADao extends BaseDao {
costructor(model) {
super(model);
}
// Other great methods related to A model
}
用法:
var sequelize = require('models/index.js);
let AModel = sequelize.import('path/to/model');
let aDao = new ADao(AModel);
aDao.myGreatMethod().then().catch();