简体   繁体   中英

How to return ID when new entry is recorded with a trigger express js and MYSQL

I am currently using express and workbench to configure a database where I can create, view and update cars.

Right now when I POST a new car it creates a new entry with the inputs manufacturer, model and price, and I use a trigger which I used inside workbench to configure a UUID for each vehicle. However, I want to be able to return this new UUID when a new record is created in my app.post function.

Here is my post function:

//Allow post methods 
app.post('/cars', (req, res) => {
    if (req.query.manufacturer && req.query.model && req.query.price) {
        console.log('Request received'); //logging to check if post request has beeen made 

        connection.connect(function(err) { //query the connection then call an SQL INSERT method to put new record in database. 
            connection.query(`INSERT INTO main.cars (manufacturer, model, price) VALUES ('${req.query.manufacturer}', '${req.query.model}', '${req.query.price}')`, function(err, result, fields) {
                if (err) res.send(err);
                if (result) res.send({manufacturer: req.query.manufacturer, model: req.query.model, price: req.query.price}); //sending the fields to the response (res)
                if (fields) console.log(fields);
                console.log(result)
            });
        });
    } else {
        console.log('Missing a parameter');
    }
});

Right now it just returns the new fields inputted in postman but not the new uuid (id) and am quite unsure how to do this, as it is created in a trigger in workbench:

CREATE DEFINER=`admin`@`%` TRIGGER `cars_BEFORE_INSERT` 
    BEFORE INSERT ON `cars` FOR EACH ROW BEGIN
        SET new.id = uuid();
    END

Query the table to get the id that was assigned to the manufacturer/model that was just inserted.

Also, use a database query with parameters rather than substituting request parameters directly into the SQL, to protect against SQL injection.

 connection.connect(function(err) { //query the connection then call an SQL INSERT method to put new record in database. connection.query('INSERT INTO main.cars (manufacturer, model, price) VALUES (?, ?, ?)', [req.query.manufacturer, req.query.model, req.query.price], function(err, result, fields) { if (err) { res.send(err); } else { connection.query('SELECT id FROM main.cars WHERE manufacturer =? AND model =?', [req.query.manufacturer, req.query.model], function(err, result) { if (err) { res.send(err); } else { res.send({ manufacturer: req.query.manufacturer, model: req.query.model, price: req.query.price, id: result[0].id }); } }); } }); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM