无法使用Sequelize和MYSQL从数组中移除项目。

huangapple go评论89阅读模式
英文:

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

我是这样解决我的问题的,因为我找不到内置的方法来做到这一点。我知道这不是最佳方法,但至少它能工作。最后,我写了一段更长的代码。

  1. 获取要删除的项目的字符串值:

    const indexString = food.dataValues.food_Name as string;
    
  2. 获取要从中删除项目的数组中的索引编号:

    const index = category.dataValues.array_Of_food?.indexOf(indexString) as number;
    
  3. 为你要定位的模型列创建一个数组变量:

    const arrayValue = category.dataValues.array_Of_food;
    
  4. 从创建的数组变量中删除该项目:

    arrayValue?.splice(index, 1);
    
  5. 使用更新方法,并将从中删除项目的数组变量作为更新传递:这将用新的数组值替换初始数组值。请记住,新的数组值包含数组列中的所有值,不包括你删除的值。

    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!

huangapple
  • 本文由 发表于 2023年1月8日 03:07:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75043075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定