NodeJs 中的 JSON_ARRAY_APPEND

问题描述 投票:0回答:2

我正在尝试更新 MySQL 的 JSON 列(比如说,

history
)。我有一个像这样的对象:

{statue: 'pending', date: 'current_date'}

使用

MODEL.update({history: {statue: 'pending', date: 'current_date'}})
它工作正常,(第一个条目)

但是当我尝试附加它时:

MODEL.update({ history: Sequelize.fn(
          'JSON_ARRAY_APPEND',
          Sequelize.col('history'),
          '$',
          `${Sequelize.fn('JSON_OBJECT', 'status', status, 'updated_at', new Date())}`
        )}) 

它不起作用。

我不想使用 JSON.stringify() (它正在使用它)。 但我想存储正确的对象数组。

任何人都可以帮忙吗

mysql node.js sequelize.js hapi
2个回答
1
投票

使用

JSON_MERGE_PRESERVE

const newHistory = {
  updated_at: new Date(),
};


await MODEL.update(
  {
    history: fn("JSON_MERGE_PRESERVE", 
      col("history"), 
      literal(`'${JSON.stringify(newHistory)}'`)
    ),
  },
  { where: { id: id } },
);

如果你的JSON是数组,这里是追加数组。

const newHistory = {
  status: 'pending',
  updated_at: new Date(),
  date: new Date(),
};


await MODEL.update(
  {
    history: fn("JSON_MERGE_PRESERVE", 
      col("history"), 
      literal(`'[${JSON.stringify(newHistory)}]'`)
    ),
  },
  { where: { id: id } },
);

如果还是报错,可以查看日志,然后尝试用原生命令MySQL运行 https://sequelize.org/docs/v6/getting-started/#logging


0
投票

我是法国人,所以我的英语会很糟糕。

您的问题的解决方案很简单。 只需删除最后一个 Sequelize.fn 周围的 `` 即可。

替换:`${Sequelize.fn('JSON_OBJECT', 'status', status, 'updated_at', new Date())}`

作者:${Sequelize.fn('JSON_OBJECT', 'status', status, 'updated_at', new Date())}

© www.soinside.com 2019 - 2024. All rights reserved.