2017-02-15 2 views
1

speichern, wie ein Datensatz innerhalb Modells Verfahren wie 'Knoten ORM-2' aktualisieren In 'Sequelize'Sequelize js: update/in Modell-Methode

In ORM-2, Just this.save() verwenden

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

Aber in Sequelize, weiß ich noch nicht

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

es weitere Methoden einfachen Befehl oder bevorzugen Ist haben?

Antwort

0

Sie sollten die addBalance Methode innerhalb instanceMethods, nicht in classMethods platzieren, da Sie

auf einer einzigen Instanz von bestimmten Modell betreiben wollen
instanceMethods: { 
    addBalance: function(howMany) { 
     howMany = Math.abs(howMany); 
     return this.set('balance', this.get('balance') + howMany).save(); 
    } 
} 

Diese Methode zurückkehren würde Promise zur aktuellen Instanz des Modells zu lösen.

EDIT

noch bessere Lösung wäre instance.increment Methode oben

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

Es wäre Rückkehr die gleiche wie die Option zu verwenden.

Verwandte Themen