I’ve created an “upsert” function (aka update and insert) in ExpressJS, the guts of which is shown here:
if (!isEdit) {
query = 'INSERT INTO comments (media_id, user_id, parent_id, comment) VALUES ($1, $2, $3, $4) RETURNING comment_id';
}
pool.query(query, [mediaId, userId, parentId, comment], (error, results) => {
Now I want to add update capabilities so I expanded the code to this:
if (isEdit) {
query = `UPDATE comments SET comment = $4 WHERE comment_id = '${commentId}'`;
} else {
query = 'INSERT INTO comments (media_id, user_id, parent_id, comment) VALUES ($1, $2, $3, $4) RETURNING comment_id';
}
pool.query(query, [mediaId, userId, parentId, comment], (error, results) => {
Unfortunately, I’m getting this error: could not determine data type of parameter $1
. I take this to mean that I must reference every single parameter provided, even though the UPDATE doesn’t require all of them.
Obviously I can expand the code to be more verbose though I’ll be repeating lots of similar code. So I’m curious if there’s a way to avoid this error I’m getting?
1