This is my server.js. I am creating a simple CRUD todo app.
I am making requests from another NodeJS script.
When I make a PUT request I found (by using breakpoints) that I get an uncaught error: source for a multiple-column UPDATE item must be a sub-SELECT or ROW() expression. Even though it is just a simple UPDATE query.
Any help is appreciated.
if (method == "PUT" && /\/todos\/(\S+)\/$/.test(url)) {
console.log("PUT request at", url);
const urlId = url.match(/\/todos\/(\S+)\/$/);
console.log(urlId);
try {
let jsonData = "";
req.on("data", chunk => {
jsonData += chunk;
});
req.on("end", async () => {
const data = JSON.parse(jsonData);
console.log([String(data["description"]), Number(urlId[1])]);
const updateTodo = await pool.query(
"UPDATE todo SET description = '$1' WHERE todo_id = $2 RETURNING *;",
[String(data["description"]), Number(urlId[1])]
); // ERROR
console.log(JSON.stringify(updateTodo));
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify(updateTodo["rows"]));
res.end();
});
} catch (err) {
console.error(err);
res.end();
}
}
Database -
CREATE DATABASE learn_restapi
CREATE TABLE todo(
todo_id SERIAL PRIMARY KEY,
description VARCHAR(255)
);
One thing I found is a bug report.
Finally, found the bug.
Rather than specifying the types in the description and todo_id in the UPDATE query, just passing them as strings work.
Also get rid of the single quotes from the query.
This is the updated async function:
req.on("end", async () => {
const data = JSON.parse(jsonData);
console.log([data["description"], urlId[1]]);
const updateTodo = await pool.query(
"UPDATE todo SET description = $1 WHERE todo_id = $2;",
[data["description"], urlId[1]]
);
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify("Todo was updated!"));
res.end();
});
I also got rid of the RETURNING statement from the query.
This seem to resolve the issue for me.