Home > Enterprise >  Can not update array field in MYSQL
Can not update array field in MYSQL

Time:01-07

I am working with MYSQL via Sequelize and I created a field for an array. I read that I could do this with DataTypes of JSON in MYSQL and set the default value to []. I did this and I would like to update that field with string values. I have tried push like this:

category.dataValues.array_Of_food?.push('item1')

 await category.save()

It won't save the added item in the database. If I use the update method like this:

await category.update({array_Of_food: category.dataValues.category_name})

This changes the array_of_food field with simply a string and not an array. How do I simply push an item into the array field if this is possible?

CodePudding user response:

It looks like you are trying to update a field in a MySQL database using Sequelize, and you want to add an item to an array stored in that field.

In order to update the array field in your database, you will need to use the $push operator provided by Sequelize. This operator allows you to append a value to an array field in the database.

Here is an example of how you can use the $push operator to add an item to the array_Of_food field in your database:

await category.update({
  array_Of_food: {
    $push: 'item1'
  }
});


await category.update({
  array_Of_food: {
    $push: ['item1', 'item2', 'item3']
  }
});

CodePudding user response:

I solved my problem by using this code:

  category.update({ array_Of_food: Sequelize.fn(
        'JSON_ARRAY_APPEND',
        Sequelize.col('array_of_food'),
        '$',
            food.dataValues.food_Name
      )}) 
  • Related