PostgreSQL char[]数组插入报错Malformed Array Literal的解决方法
问题
尝试将字符串数据插入PostgreSQL的char[]类型列时,返回“Malformed Array Literal”错误。相关代码如下:
后端代码(Node.js)
async function insertTag(req, res) { return db.none('UPDATE user_account SET tag_property = $1 WHERE email = $2', [req.body.tag_id, req.body.email]) .then(function () { res.status(200) .json({ status: 'success', message: 'Updated user', }); }) .catch(error => { console.log(error) }); }
前端代码
tagIdInput: '', InsertTagUserAccount(){ fetch('http://192.168.1.51:3000/api/v1/tag_insertion', { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email : 'monemail@gmail.com', tag_id : '{' + this.tagIdInput + '}', }), }) .then(response => response.json()) .then(json => console.log(json)); }
解决方案
方法1:前端传递数组,后端直接绑定
PostgreSQL的数组类型支持直接接收JavaScript数组,无需手动拼接字符串格式。
修改前端代码,直接传递数组:
InsertTagUserAccount(){ fetch('http://192.168.1.51:3000/api/v1/tag_insertion', { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email : 'monemail@gmail.com', // 单个标签转成数组;若为多个标签,可按分隔符分割后转数组 tag_id : [this.tagIdInput], }), }) .then(response => response.json()) .then(json => console.log(json)); }
后端代码无需修改,pg库会自动将JavaScript数组转换为PostgreSQL可识别的数组格式。
方法2:使用PostgreSQL数组构造函数(适合无法修改前端的场景)
如果前端必须传递字符串,后端可通过PostgreSQL的数组构造函数处理:
async function insertTag(req, res) { return db.none('UPDATE user_account SET tag_property = array[$1] WHERE email = $2', [req.body.tag_id, req.body.email]) .then(function () { res.status(200) .json({ status: 'success', message: 'Updated user', }); }) .catch(error => { console.log(error) }); }
若tagIdInput是逗号分隔的多标签字符串,可改用string_to_array函数:
UPDATE user_account SET tag_property = string_to_array($1, ',') WHERE email = $2
内容的提问来源于stack exchange,提问作者Barre Mathis
相关产品推荐
相关产品推荐

