3

I would like to update a database record using sequelize.js and mysql2 I do not have access to the models folder or either they have not been made so is there a way to update can't find solution all solutions are that i checked are with model name dot update

var Book = db.define(‘books’, {
 title: {
   type: Sequelize.STRING
 },
 pages: {
   type: Sequelize.INTEGER
 }
})


Book.update(
   {title: req.body.title},
   {returning: true, where: {id: req.params.bookId} }
 )
 .then(function([ rowsUpdate, [updatedBook] ]) {
   res.json(updatedBook)
 })
 .catch(e => console.log(e));

I would like your expert solution on that please

Muhammad Sharif
  • 406
  • 6
  • 17

1 Answers1

6

For latest documentation based on version refer to Sequelize ORM.

Update - v6

You can use both query model(preferred) as well as raw queries to achieve this.

// Using query model(User)
await User.update({ y: 42 }, {
  where: {
    x: 12
  }
});

// Using raw query
const [results, metadata] = await sequelize.query("UPDATE users SET y = 42 WHERE x = 12");
// Results will be an empty array and metadata will contain the number of affected rows.

Old - v3

sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread(function(results, metadata) {
  // Results will be an empty array and metadata will contain the number of affected rows.
})

Reference: Sequelize Raw Query

Dark Knight
  • 6,116
  • 1
  • 15
  • 37