简体   繁体   English

在 Postgres 中使用 Sequelize 更新特定的 JSON 字段

[英]Update a particular JSON field using Sequelize in Postgres

I have a "user" table with one of the fields "info" being a JSON structure:我有一个“用户”表,其中一个字段“信息”是 JSON 结构:

user table has these fields: id, name, info, created用户表有以下字段:id、name、info、created

info filed has this structure:信息归档具有以下结构:

info: { email, password, device: { type, token } }信息:{电子邮件,密码,设备:{类型,令牌}}

How can I use Sequelize to update the token field for a specific user in Postgres?如何使用 Sequelize 更新 Postgres 中特定用户的令牌字段?

I know that this is a question about sequelize.js , but I don't know much about it, so let me give a general answer about postgresql (feel free to ignore it).我知道这是一个关于sequelize.js的问题,但我对它了解不多,所以让我给出一个关于 postgresql 的一般性答案(可以随意忽略它)。 First, postgresql does not support modifying json values.首先,postgresql 不支持修改json值。 json columns should mostly be used to store JSON data in the database and not to manipulate JSON data. json列主要用于在数据库中存储 JSON 数据,而不是操作 JSON 数据。 If you really want to manipulate JSON data in the database then you have to use a jsonb column.如果您真的想操作数据库中的 JSON 数据,那么您必须使用jsonb列。 jsonb can be modified with the help the jsonb_set function and the || jsonb可以与帮助修改jsonb_set功能和|| operator.操作员。 In your case, if you can run raw SQL queries, you could do something like this:在您的情况下,如果您可以运行原始 SQL 查询,则可以执行以下操作:

UPDATE "user"
SET info = jsonb_set(info,'{device,token}','123')
WHERE id = 31;
user.findOne({where: {id: 31}}).then((u) => {
u.device.update(info: {type, token})

});

This is a user table.这是一个用户表。 with id of 31 to update the value of type and token id 为 31 来更新 type 和 token 的值

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

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