Reputation: 65
I am using MYSQL
through Sequelize
to build a node.js
application with typescript
. I created a table
and the table
has a field which I made a JSON
dataType and made it an array
by default. I have been able to push items into the array
. I would like to remove items from the array
, how can I achieve this?
I tried using await category.update({array_Of_food:Sequelize.fn('array_remove',Sequelize.col('array_of_food'),JSON.stringify(category.dataValues.array_Of_food && category.dataValues.array_Of_food[index]))})
I got an error that array_remove
does not exist.
Upvotes: 0
Views: 381
Reputation: 65
I solved my problem this way since I couldn't find an inbuilt way of doing it. I know this is not the best method but at least it works. At the end, I wrote a longer code.
1.Get the string value
of the item you want to remove.
const indexString = food.dataValues.food_Name as string;
2.Get the index number
of that item inside the array you wish to delete it from:
const index = category.dataValues.array_Of_food?.indexOf(indexString) as number;
3.Create a variable for the the array out of the model colum that you are targeting.
const arrayValue = category.dataValues.array_Of_food
4.Remove that item from the array variable that you crceated:
arrayValue?.splice(index, 1);
5.Use the update method and pass the array variable you deleted the item from as the update: This will replace the initial array values with the new array values. Remember that the new array values contain all the values in the array column excluding the value you deleted.
await category.update({array_Of_food: arrayValue})
This worked!
Upvotes: 2