Home > Blockchain >  Sharing user_id value between two MySql table
Sharing user_id value between two MySql table

Time:10-19

I'm working on my middleware AuthController.js below. The middleware is part of a CRUD app. I created exports.create which when requested will collect the first name and last name from the CRUD form. Once collected the MySql INSERT query, will insert the data on the MySql user table which is working fine.

What I cannot achieve and I need help is that together with the first name and last name info I want to insert also the variable { user_id: decoded.id }, decoded.id is a variable which take the user_id value from another MySql table called login.

When I request export.create the following error shows on the terminal:

(node:18780) UnhandledPromiseRejectionWarning: TypeError: argument callback must be a function when provided

Basically I want that the value under user_id column from the login table is transferred to the user_id column on user table. Thank for any help.

exports.create = async (req, res, next) => {
    if (req.cookies.jwt) {
        try {
            //1)verify the token
            var decoded = await promisify(jwt.verify)(req.cookies.jwt,
                process.env.JWT_SECRET
            );
            
            // console.log(decoded);
            const { first_name, last_name } = req.body;

            connection.query('INSERT INTO user SET first_name = ?,last_name = ?', { user_id: decoded.id }, [first_name, last_name,], (err, rows) => {
                if (!err) {
                    res.render('add-crew', { alert: 'Crew member added succesfully!' });
                } else {
                    console.log(err);
                }
                console.log('The data from user table:\n', rows);

            });

        } catch (error) {
            console.log(error);
            return next();
        }
    }
};

CodePudding user response:

The connection.query function takes in two to three arguments: the SQL statement, (the values) and the callback. Here, the function is taking four arguments, so it thinks [first_name, last_name,] is the callback.

What you can do is:

...
connection.query('INSERT INTO user SET user_id = ?, first_name = ?,last_name = ?', [decoded.id, first_name, last_name,], (err, rows) => {
    if (!err) {
        res.render('add-crew', { alert: 'Crew member added succesfully!' });
    } else {
        console.log(err);
    }
    console.log('The data from user table:\n', rows);
});
...

I hope this is what you are looking for.

Edit you could also do:

...
connection.query('INSERT INTO user SET ?', {user_id: decoded.id, first_name: first_name, last_name: last_name}, (err, rows) => {
    if (!err) {
        res.render('add-crew', { alert: 'Crew member added succesfully!' });
    } else {
        console.log(err);
    }
    console.log('The data from user table:\n', rows);
});
...
  • Related