NodeJS 如何更新嵌套对象中的数组属性?

r8xiu3jd  于 2023-01-01  发布在  Node.js
关注(0)|答案(1)|浏览(138)

我需要更新嵌套对象中jsonb postgresql的一个数组。我似乎不能让它工作。到目前为止,我已经尝试了许多不同的方法,但都没有成功。我正在尝试通过与调度ID进行比较来更新更干净的数组。

    • 表格**
id(serial) | info(jsonb)
    • 服务器. js**
var contractorInfo = {
    "id": cleanerid,
    "fname": fname,
    "lname": lname,
    "avatar":avatar
  }

//id
var laveid = 'order_cbs1l';
    • 返回空值,不更新**
"UPDATE users SET info = JSONB_SET(info, '{schedule,cleaner}', '"+JSON.stringify(contractorInfo)+"') WHERE info->'schedule'->>'id'='"+laveid+"' RETURNING*"
    • 返回空值,不更新**
"UPDATE users SET info = JSONB_SET(info, '{schedule,cleaner}', '"+JSON.stringify(contractorInfo)+"') WHERE info #>> '{schedule,id}' = '"+laveid+"' RETURNING*"
    • json对象**
{
  "dob": "1988-12-11",
  "type": "seller",
  "email": "johndoe@gmail.com",
  "phone": "5553766962",
  "avatar": "image.png",
  "schedule": [
    {
      "id": "order_cbs1l",
      "pay": "230",
      "date": "2022-12-29",
      "status": "Available",
      "address": "234 Eleventh Street, Mildura Victoria 3500, Australia",
      "cleaner": {
        "id": "",
        "fname": "",
        "lname": "",
        "avatar": ""
      },
      "end_time": "10:15",
      "start_time": "01:00",
      "total_hours": "33300000",
      "paymentIntentId": "pi_3KJnrEFzZWeJoxzV1yUdGLQ8"
    }
  ],
  "last_name": "doe",
  "first_name": "john",
  "countrycode": "Canada: +1",
  "countryflag": "iti__ca",
  "date_created": "2022-11-12T19:44:36.714Z"
}
67up9zun

67up9zun1#

我看到的问题是where类与所讨论的行不匹配。因为“schedule”是一个数组,所以应该替换为

WHERE info->'schedule'->>'id'='"+laveid+"'

WHERE info->'schedule'-> 0 ->>'id'='"+laveid+"'

因为这将引用“schedule”数组中的第一个元素。由于该数组只有一个元素,您可能还需要考虑通过将json存储为

{
  "dob": "1988-12-11",
  "type": "seller",
  "email": "johndoe@gmail.com",
  "phone": "5553766962",
  "avatar": "image.png",
  "schedule": {
    "id": "order_cbs1l",
    "pay": "230",
    "date": "2022-12-29",
    "status": "Available",
    "address": "234 Eleventh Street, Mildura Victoria 3500, Australia",
    "cleaner": {
      "id": "",
      "fname": "",
      "lname": "",
      "avatar": ""
    },
    "end_time": "10:15",
    "start_time": "01:00",
    "total_hours": "33300000",
    "paymentIntentId": "pi_3KJnrEFzZWeJoxzV1yUdGLQ8"
  },
  "last_name": "doe",
  "first_name": "john",
  "countrycode": "Canada: +1",
  "countryflag": "iti__ca",
  "date_created": "2022-11-12T19:44:36.714Z"
}

在这种情况下,原来的where子句将起作用。

相关问题