Sequelize ClassMethods

时间:2017-04-05 19:28:53

标签: controller sequelize.js

我正在尝试使用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);

感谢您提供任何帮助,我是sequelize的新手

1 个答案:

答案 0 :(得分:1)

您正在考虑实例方法。实例方法中的this将是一个帐户。

使用classMethods this是自己的类。当您需要定义关于许多实例的自定义功能时,类方法很有用。

在您的示例中,您可能希望每月运行一次功能,并向一定金额以下的储蓄帐户收取费用(我的银行会这样做!)

classMethods: {
  async findAndCharge(n) {
    const accounts = await this.findAll({ where: { balance: { $lte: n } } });

    for (const account of accounts) {
      await account.charge()
    }
  }
 }

这是一个有点人为的例子,但正如您所看到的,类方法中的thisAccount(带上限)而不是account小写。

在其他情况下,这有时是一种静态方法。

在您的情况下,您应该切换到instanceMethods

相关问题