Sequelize js:更新/保存模型的方法

时间:2017-02-15 16:00:51

标签: javascript node.js sequelize.js

如何更新模型的方法,如节点orm-2'在' Sequelize'

在orm-2中,只需使用 this.save()

即可
var users = db.define('users',
    {
        id          : { type: 'serial', key: true },
        username    : { type: 'text', size: 25, unique: true, required: true },
        balance     : { type: 'integer', defaultValue: 0 },
    }, {
        timestamp: true,
        methods: {
            addBalance: function (howMany) {
                howMany = Math.abs(howMany);
                this.balance += howMany;
                this.save(function (err) {
                    console.log("added money to "+this.username+" : "+howMany);
                });
            }
        }
    });

但是在Sequelize中,我还不知道

var wallet = sequelize.define('wallet', {
    balance : { type: Sequelize.INTEGER, defaultValue: 0, validate: { min: 0 } }
}, {
    timestamps: true,
    classMethods: {
        addBalance: function (howMany) {
            howMany = Math.abs(howMany);
            this.balance += howMany;
            //UPDATE Or SAVE HERE...
        }
    }
});

是否有简单的命令或更喜欢其他方法?

1 个答案:

答案 0 :(得分:1)

您应该将addBalance方法放在instanceMethods内,而不是放在classMethods中,因为您要对指定模型的单个实例进行操作

instanceMethods: {
    addBalance: function(howMany) {
        howMany = Math.abs(howMany);
        return this.set('balance', this.get('balance') + howMany).save();
    }
}

此方法将返回Promise解析为当前模型实例。

修改

更好的解决方案是使用instance.increment方法

addBalance: function(howMany) {
    howMany = Math.abs(howMany);
    return this.increment('balance', { by: howMany });
}

它将返回与上面的选项相同的内容。