【发布时间】:2017-08-31 14:08:35
【问题描述】:
我正在尝试使用 sequelize 和 nodejs 为银行账户的存款和取款构建一个简单的 api,但我对如何使用我放在 classmethods 中的方法有点困惑。谁能告诉我如何在我的控制器中使用它。下面是我的模型
'use strict';
module.exports = function(sequelize, DataTypes) {
var Account = sequelize.define('Account', {
name: DataTypes.STRING,
balance: DataTypes.DOUBLE,
pin: DataTypes.INTEGER,
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
},
addMoney: function(amount){
amount = Math.abs(amount);
return this.increment('balance', {by : amount}).save();
},
withdrawMoney: function(amount){
amount = Math.abs(amount);
return this.decrement('balance', {by : amount}).save();
}
}
});
return Account;
}
以下是我的控制器,但我不确定如何在控制器中使用我的类方法
var models = require('../models/index');
module.exports = {
newAccount(req, res, next){
models.Account.create({
balance: req.body.balance,
note: req.body.note,
pin: req.body.pin,
}).then(function(account){
res.json(account);
}).catch(function(error){
res.json(error)
})
},
listAccount(req, res, next){
models.Account.
findAll({
})
.then(function(accounts) {
res.status(200).send(accounts);
}).catch(function(error){
res.status(400).send(error)
});
}
}
这是我的路线以防万一,这只是避免发布太多代码的路线
app.get('/accounts', accountCtrl.listAccount);
app.post('/account/new', accountCtrl.newAccount);
app.put('/account/:id', accountCtrl.updateAccount);
app.delete('/account/:id', accountCtrl.removeAccount);
感谢您的帮助,我是续集的新手
【问题讨论】: