1

Here's my code. First I defined user table

'use strict';
const db = require('../db');
const DataTypes = db.Sequelize;

module.exports = db.define('user', {
    firstName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    lastName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    number1: {
        type: DataTypes.STRING
    },
    number2: {
        type: DataTypes.STRING
    }
})

Here I want to update number1 and number2 by an array which saves all the numbers

var arr = [1,2]
User.findAll(req.body)
.then(users => {
    for(let i=0; i<arr.length; i++){
        users.update({
            'number'+ (i+1): '2',
        })
    }
})

So this give me a syntax error, which means sequelize doesn't recognize this part 'number'+ (i+1).

If I use template string like this number${i+1}, it still cannot work.

but when I try "number1", it works! Why? and how do I fix this?

Paul
  • 93
  • 2
  • 15

1 Answers1

2

This is not an issue with Sequelize, this is an issue with your JavaScript syntax (hence the syntax error).

In order to get a "dynamic" or "computed" key for the object that you pass to users.update, you need to use [] for computed property names.

  users.update({
    [`number${i+1}`]: '2',
  })
Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90