sequelize update example
Example 1: sequelize update sql
const Tokens = db.define('tokens', {
token: {
type: sequelize.STRING
}
});
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) {
const foundItem = await model.findOne({where});
if (!foundItem) {
const item = await model.create(newItem)
return {item, created: true};
}
const item = await model.update(newItem, {where});
return {item, created: false};
}
Example 3: sequelize update
var Book = db.define(‘books’, {
title: {
type: Sequelize.STRING
},
pages: {
type: Sequelize.INTEGER
}
})
Book.update(
{title: req.body.title},
{where: req.params.bookId}
)
Example 4: update data in sequelize
const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}
models.Locale.update(objectToUpdate, { where: { id: 2}})
Example 5: update data in sequelize
const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}
models.Locale.findAll({ where: { title: 'Hello World'}}).then((result) => {
if(result){
result[0].set(objectToUpdate);
result[0].save();
}
})
Example 6: update column with find sequelize
Project.find({ where: { title: 'aProject' } })
.on('success', function (project) {
if (project) {
project.update({
title: 'a very different title now'
})
.success(function () {})
}
})