2

How to update a record inside model's method like 'node orm-2' In 'Sequelize'

In orm-2, Just use 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);
                });
            }
        }
    });

But in Sequelize, I don't know yet

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...
        }
    }
});

Is it have simple command or prefer another methods?

1 Answer 1

1

You should place the addBalance method inside instanceMethods, not in classMethods, because you want to operate on a single instance of specified model

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

This method would return Promise resolving to current instance of model.

EDIT

Even better solution would be to use instance.increment method

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

It would return the same as the option above.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.