简体   繁体   English

用 Node 标准替换字符串(无查询)Sequelize

[英]Replace string with Node standard (no query) Sequelize

I have Node server that uses MariaDB (MySQL) via Sequelize.我有通过 Sequelize 使用 MariaDB (MySQL) 的节点服务器。
I have some rows in my db that looks like this, for example:我的数据库中有一些行看起来像这样,例如:

Id ID clips剪辑
1 1个 ["videoId123456","videoId8910111213"] ["videoId123456","videoId8910111213"]
2 2个 ["videoId123456"] [“videoId123456”]
3 3个 [] []
4 4个 ["videoId123456"] [“videoId123456”]

The "clips" column is a string, but in an array structure. “剪辑”列是一个字符串,但在数组结构中。

My task is to find a way to remove specific videoId from the clips column.我的任务是找到一种方法从剪辑列中删除特定的 videoId。 For example, if the API route gets the Id "videoId123456", it will be deleted from rows 1,2,4.例如,如果 API 路由获得 Id“videoId123456”,则它将从第 1、2、4 行中删除。 If it gets the Id "videoId8910111213" it will be deleted from row 1.如果它获得 Id“videoId8910111213”,它将从第 1 行中删除。

I know how to do it by pure MySQL, something like:我知道如何通过纯 MySQL 来做到这一点,例如:

UPDATE player
SET clips = REPLACE(clips ,'"videoId1234567"','')
WHERE clips LIKE '%"videoId1234567"%';

I know I can run pure SQL commands with Sequelize as string like:我知道我可以使用 Sequelize 作为字符串运行纯 SQL 命令,例如:

await sequelize.query(
`   UPDATE player
    SET clips = REPLACE(clips ,'"videoId1234567"','')
    WHERE clips LIKE '%"videoId1234567"%';
`, {
  type: QueryTypes.UPDATE
});

But I wonder if there any way to do it by pure Sequelize, something like:但我想知道是否有任何方法可以通过纯 Sequelize 来做到这一点,例如:

player.update({
  'clips': 'clips.replace('"videoId1234567"','')'
   where: { 'clips': [Op.like]: '"videoId1234567"' }
});

Thanks.谢谢。

You can use Sequelize.fn amd Sequelize.col to achieve the goal to use the replace SQL function:您可以使用Sequelize.fn amd Sequelize.col来实现使用replace SQL function 的目标:

player.update({
  clip: Sequelize.fn('replace', Sequelize.col('clip'), '"videoId1234567"','')
}, {
   where: { clip: { [Op.like]: '"videoId1234567"' } }
});

PS It would be better not to just replace substrings in this JSON-like array and prefer using SQL functions that can work with JSON to work with an array (if it's applicable to MariaDB). PS 最好不要只替换这个类似 JSON 的数组中的子字符串,而更喜欢使用可以与 JSON 一起使用的 SQL 函数来处理数组(如果它适用于 MariaDB)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM