I am trying to build an update api, which I have tested in postman with both put and post. I have an sql database, where I defined all my columns and stored inside of userdata as objects.
Then I use a function to loop through the key, value pair of objects and check if the value is not undefined. Because if the value is not undefined then it should update with the following mysql procedure: 'UPDATE users SET WHERE id=undefined'
However, It gives me an error, every time I try to run the endpoint in postman.
//create route for updating user
app.put('/updateUser', (req, res) => {
//create updateQuery command for database
let updateQuery = "UPDATE users SET ";
//create variable for userdata
let userdata = {
'firstname':req.body.name,
'lastname':req.body.lastname,
'email':req.body.email,
'password':req.body.password,
'year':req.body.year,
'gender':req.body.gender,
'prefer':req.body.prefer,
'interest':req.body.interested,
'about':req.body.about,
'id':req.body.id
};
//loop through key and value pair of objects in userdata
for (const [key, value] of Object.entries(userdata)) {
if(value != undefined){
updateQuery += key + ' = ' + value + ",";
}
}
updateQuery = updateQuery.slice(0, -1);
updateQuery += " " + 'WHERE id='+req.body.id;
connecter.query(updateQuery,
//treat the post from the frontend
(err, result) => {
//check if succes is true or false
if(err) {
res.send({ succes: false });
throw err;
} else {
res.send({ succes: true});
}
});
});
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=undefined' at line 1",
sqlState: '42000',
index: 0,
sql: 'UPDATE users SET WHERE id=undefined'
Aucun commentaire:
Enregistrer un commentaire