Linking the user on the create

How do you link the user to the creation of a record that has a relation (one to one, one to many, many to many).
I tried the snippet suggested by IA but it doesn’t work.
NB: name of the field is user or in case of many is users

Snippet:
`// ./middlewares/linkUserMiddleware.js

module.exports = async (ctx, next) => {
// Check if the request is for a create action
if (ctx.request.method === ‘POST’) {
// Get the currently authenticated user
const user = ctx.state.user;

    if (!user) {
        return ctx.unauthorized('You must be logged in to create an entry.');
    }

    // Debugging: Log the user ID
    console.log('Authenticated User ID:', user.id);

    // Link the user to the data being created
    if (ctx.request.body.data) {
        ctx.request.body.data.user = user.id; // Adjust 'user' to match your model
    } else {
        return ctx.badRequest('Invalid data format.');
    }
}

// Proceed to the next middleware or controller
await next();

};
`

This topic has been created from a Discord post (1283449967272263782) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord