sequelize query for update code example

Example 1: sequelize update sql

const Tokens = db.define('tokens', {
    token: {
        type: sequelize.STRING
    }
});
// Update tokens table where id
Tokens.update(
          { token: 'new token' },
          { where: {id: idVar} }
     ).then(tokens => {
          console.log(tokens);
     }).catch(err => console.log('error: ' + err));

Example 2: create or update in sequelize

async function updateOrCreate (model, where, newItem) {
    // First try to find the record
   const foundItem = await model.findOne({where});
   if (!foundItem) {
        // Item not found, create a new one
        const item = await model.create(newItem)
        return  {item, created: true};
    }
    // Found an item, update it
    const item = await model.update(newItem, {where});
    return {item, created: false};
}

Tags:

Misc Example