英文:
Can not remove an item from an array using Sequelize and MYSQL
问题
我正在使用Sequelize
通过MYSQL
构建一个node.js
应用程序,使用typescript
。我创建了一个table
,这个table
有一个字段,我将其设为了JSON
数据类型,并默认将其设为了一个array
。我已经能够向这个array
中添加项目。我想从这个array
中删除项目,该如何实现?
我尝试使用以下代码:
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]))
})
但我收到了一个错误,提示array_remove
不存在。
英文:
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.
答案1
得分: 2
我是这样解决我的问题的,因为我找不到内置的方法来做到这一点。我知道这不是最佳方法,但至少它能工作。最后,我写了一段更长的代码。
-
获取要删除的项目的字符串值:
const indexString = food.dataValues.food_Name as string;
-
获取要从中删除项目的数组中的索引编号:
const index = category.dataValues.array_Of_food?.indexOf(indexString) as number;
-
为你要定位的模型列创建一个数组变量:
const arrayValue = category.dataValues.array_Of_food;
-
从创建的数组变量中删除该项目:
arrayValue?.splice(index, 1);
-
使用更新方法,并将从中删除项目的数组变量作为更新传递:这将用新的数组值替换初始数组值。请记住,新的数组值包含数组列中的所有值,不包括你删除的值。
await category.update({array_Of_food: arrayValue});
这个方法有效!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论