Update a table's data from an another table's post route

Hello everyone,

I’m trying to update a model’s data from another table’s post route.

Here is the code I have:

router.post(
	"/bookings",
	permissionMiddlewareCreator.create(),
	(request, response, next) => {
		const recordCreator = new RecordCreator(bookings);
		const tableRecordUpdater = new RecordUpdater(tables);

		// Get the values of the input fields entered by the admin user.
		request.body.data.attributes.accessLink = `lords://${uuid()}`;

		recordCreator
			.deserialize(request.body)
			.then((recordToCreate) => recordCreator.create(recordToCreate))
			.then((record) => {
				console.log(record.dataValues.bookingId);
				return recordCreator.serialize(record);
			})
			.then((recordSerialized) => response.send(recordSerialized))
			.catch((next) => {
				console.log(next);
			});
	}
);

It is at the line where I currently have console.log(record.dataValues.bookingId); that I want to update the model tables.

I have already added a RecordUpdater for that model. However, I am not sure how I can generate de data I need to feed that function. From this link https://docs.forestadmin.com/documentation/v/v6/reference-guide/routes/default-routes#update-a-record, I do not know how I can build the request.body object from the bookings’ post route.

If any of you has any suggestions, it would be great.

Thanks

Hi @daweido !
Do you want to update the data every time a record of this type is created ? If so, you could use hooks to achieve that.

1 Like

Thanks @Nicolas_Sailly, do you know how I can query another tables from within a hook to update a certain element based on its PK ?

You mean retrieving a PK from another table and then use it to update another one ?

I actually have all the ids needed. I guess using this https://stackoverflow.com/a/29313764 will do the trick, where I just need to replace create with update, right ?

Yes, if you have a relationship between your tables it should be good !

@daweido let me know if it worked so that I can clause the issue :slight_smile:

Thank you @Nicolas_Sailly .

I’m actually still stuck. I added a hook, and added an update to the second model, but I don’t see the changes made.

Here is the code I have:

hooks: {
				afterCreate: async (booking, option) => {
					await sequelize.models.tables.update(
						{ bookingId: booking.bookingId },
						{
							where: {
								tableId: +booking.tableIdKey,
							},
						}
					);
				},
			},

Am I doing something wrong ?

Hello @daweido,

Do you know if your code is executed when you create a booking? Can you add a log and check if it shows up on creation?

Hello @GuillaumeGautreau,

I have indeed added a console.log with a findOne to check if I do have access to the model or not, and I do.

However, when it comes to updating, it does not work.

Can you activate the logging on sequelize, to check the different queries that are run on your DB? This way, you’ll able to check if the generated query looks right.

In your model/index.js file you can see that logging is active when the environment variable NODE_ENV is set to development.

So if you define this environment variable, you should be able to see the queries. Could you please paste the query matching the create and the update?

Oh I didn’t know we could do that ! That’s nice.

It still doesn’t work.

Here is my updated code for the hooks:

hooks: {
				afterCreate: (booking, option) => {
					console.log("/n/n/n/n/n/n/n");
					sequelize.models.tables
						.update(
							{ bookingId: booking.bookingId },
							{
								where: {
									tableId: +booking.tableIdKey,
								},
							}
						)
						.then((res) => {
							console.log("res", res);
						});
					console.log("/n/n/n/n/n/n/n");
				},
			},

And here are the logs for the creation request:

Executing (default): INSERT INTO `bookings` (`bookingId`,`bookedDate`,`status`,`noShow`,`paidFine`,`accessLink`,`tableId`,`userId`) VALUES (DEFAULT,?,?,?,?,?,?,?);
/n/n/n/n/n/n/n
/n/n/n/n/n/n/n
(node:96337) Warning: a promise was created in a Promise.each handler at node:internal/timers:463:21 but was not returned from it, see http://goo.gl/rRqMUw
    at Function.Promise.attempt.Promise.try (/Users/daweido/Projects/lords/lords-backoffice/node_modules/bluebird/js/release/method.js:29:9)
res [ 0 ]

Could you wait for the promise to end, in order to avoid the warning?

Maybe there is an error in your query, but as the promise is not correctly handled it may be hidden.

afterCreate: async (booking, option) => {
					console.log("/n/n/n/n/n/n/n");
					await sequelize.models.tables
						.update(
							{ bookingId: booking.bookingId },
							{
								where: {
									tableId: +booking.tableIdKey,
								},
							}
						)
						.then((res) => {
							console.log("res", res);
						});
					console.log("/n/n/n/n/n/n/n");
				},
1 Like

Thank you for your help @GuillaumeGautreau and @Nicolas_Sailly, I just found the reason why it did not work.

The column bookingId, is the name of the real column in my database, but in my model it a foreign key defined as so:

Tables.belongsTo(models.bookings, {
			foreignKey: {
				name: "bookingIdKey",
				field: "bookingId",
			},
			as: "booking",
		});

Here is the working code:

afterCreate: async (booking, option) => {
					await sequelize.models.tables.update(
						{ bookingIdKey: booking.bookingId },
						{
							where: {
								tableId: +booking.tableIdKey,
							},
						}
					);
				},

Thank you all for your help.