我在我的应用程序中使用 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列时不遇到此错误?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要将字符串数组插入到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