[英]How to process data received as an array from req.body
我有表 a 和 b。 两个数据同时创建,b接收a的id作为FK。
在这里,可以一次向表 b 添加多行,作为 req.body 接收的值如下。
{
"userId": 1,
"a1": "ccc",
"a2": "ddd",
"typeId": [1, 2, 3]
"count": [60, 100, 5]
}
有没有办法处理查询中作为数组接收的数据,如下所示?
INSERT INTO data (a_id,typeId,count)
VALUES (0,1,60), (0,2,100), (0,3,5),
我试过以下方法:
DAO.js
const createRecordData = async(userId, a1, a2, typeId, count) => {
await myDataSource.query(
`INSERT INTO a (user_id,a1,a2)
VALUES(?,?,?)`,
[userId, a1, a2]
);
const datas = await myDataSource.query(
`INSERT INTO data (a_id,typeId,count)
VALUES ${typeId.map((tID) =>"(" + "((SELECT LAST_INSERT_ID())" + "," + tID + "," + count.map((c) => c + ")" ).join(","))}`,
[typeId, count]
);
return data;
};
但这会返回如下错误:
SyntaxError: Unexpected string in JSON at position 101
=== 我试过以下方法。
const createRecordData = async(userId, a1, a2, typeId, count) => {
await myDataSource.query(
`INSERT INTO a (user_id,a1,a2)
VALUES(?,?,?)`,
[userId, a1, a2]
);
const typeAndCount = typeId.map((type, index) => `((SELECT LAST_INSERT_ID()),${type},${count[index]}),`).join("");
const datas = await myDataSource.query(
`INSERT INTO data (a_id,typeId,count)
VALUES ${typeAndCount}`,
[typeId, count]
);
return data;
};
这将返回该错误。
"typeId.map is not a function"
我究竟做错了什么? 我需要帮助。
如果你知道 typeId 和 count arrays 总是有相同的长度,你可以这样做。 否则,可能会涉及一些其他检查
const data = { "userId": 1, "a1": "ccc", "a2": "ddd", "typeId": [1, 2, 3], "count": [60, 100, 5] }; const processData = (data) => { const {typeId, count} = data; const typeAndCount = typeId.map((type, index) => `(0,${type},${count[index]}),`).join(""); return `INSERT INTO data (a_id,typeId,count) VALUES ${typeAndCount}`; }; console.log(processData(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.