首頁  >  問答  >  主體

在將數組插入PostgreSQL列時出現了錯誤的數組字面量

我在我的應用程式中使用 objection.js。

在嘗試將字串陣列插入PostgreSQL資料庫列時,遇到了一個問題。該列的定義如下:

path TEXT[] NOT NULL

這是模式:

path: { type: 'array', items: { type: 'string' }, notNull: true }

我想使用upsertGraphAndFetch(objection.js)更新表格列,但在更新和插入時,插入列path時出現錯誤

return NotificationUserOption.query().upsertGraphAndFetch(
        { userId: ctx. user, path, groupId, option },
        { insertMissing: true },

當我傳遞類似於['chat']的path時

await updateGlobalChatNotificationOptIn({
      variables: {
        path: ['chat'],
        option: updatedGlobalChatNotificationOptIn ? '30MinSummary' : 'off',
      },
    })
  }

然而,當我嘗試使用這段程式碼插入數組時,遇到了以下錯誤:

陣列文字格式錯誤:“[”chat“]” “[”必須明確指定數組維度。

我嘗試使用單括號('{chat}')和雙括號([['chat']]),但都無效。

如何正確格式化數組文字,以便在插入PostgreSQL列時不遇到此錯誤?

P粉141925181P粉141925181236 天前472

全部回覆(1)我來回復

  • P粉009828788

    P粉0098287882024-01-30 11:48:17

    要將字串陣列插入到PostgreSQL的TEXT[]類型的欄位中,您需要將JavaScript陣列轉換為字串表示形式,使用花括號和雙引號包裹每個元素。

    Objection.js中執行以下操作:

    // 将数组转换为字符串表示形式
    const pathArray = ['chat'];
    const pathString = `{${pathArray.join(',')}}`;
    
    // 使用Objection.js将数据插入数据库
    await NotificationUserOption.query().upsertGraphAndFetch(
      { userId: ctx.user, path: pathString, groupId, option },
      { insertMissing: true }
    );

    現在TEXT[]將不會出現任何"malformed array literal"錯誤。從資料庫查詢資料時,Objection.js將處理將其轉換回JavaScript陣列。

    #Apache-Age #posgresql #graphql #objection.js

    回覆
    0
  • 取消回覆