I am trying to create an Express router route which allows me to update a MySQL schema containing data about 'members' (members of clubs). The members table in the schema contains many columns, e.g. member_id, forename, surname, address, etc, etc. I have created an Express route which allows me to update (using the Sequelize update method) a single column in the table, by specifying the specific column - in my example below, the column 'forename'. This code has been successfully tested using Insomnia.
router.put("/byId/", async (req, res) => {
const { forename, member_id } = req.body
await Members.update({forename: forename}, {where:{ member_id: member_id}})
res.json(forename)
});
Whilst I could add all the table columns in the const definition and in the Sequelize update method, I was wondering if there is a way that I can code this so that it reads whatever key value pairs it finds in the JSON and updates all fields for which key value pairs exist.
I do something similar to the approach I have in mind when creating a member, using the router below - where individual columns are not specified specifically:
router.post("/", async (req, res) => {
const member = req.body;
await Members.create(member);
res.json(member);
});
So I attempted to modify my update router as follows, following a similar approach to the create code:
router.put("/byId/", async (req, res) => {
const member = req.body
await Members.update(member, {where:{ member_id: member_id}})
res.json(member)
});
However this threw a "Error: Failure when receiving data from the peer" error in Insomnia, and crashed the Node server with an error "ReferenceError: member_id is not defined".
This latter error makes sense to me - I'm trying to update a record for a specific member_id, but don't define member_id. I'm just not clear exactly how I can define that whilst retaining the 'update all fields for which key value pairs exist' functionality I'm looking for. Nor whether resolving that will be enough to make this route work as I'd hoped.
CodePudding user response:
Per Dave's comment:
The member ID is a property of
member
and must be accessed as such.
It was an easy fix:
router.put("/byId/", async (req, res) => {
const member = req.body
await Members.update(member, {where:{ member_id: member.member_id}})
res.json(member)
});