javascriptnode.jsexpressnode-mysql2

Node/Express error: TypeError: Cannot read property 'then' of undefined


I submit a form to my express server and I get the following error:

TypeError: Cannot read property 'then' of undefined

The 'then' refers to the then in the (truncated) code below (a post method in a controller file).

exports.postAddVehicle = (req, res, next) => {
    //const id = null;
    //car table
    const model_year = req.body.model_year;
    const make = req.body.make;
    ...
    const car = new Car(
        null, model_year, make, model, 
        miles, color, transmission, layout, engine_type,
        car_photo_url, car_price, sale_status, for_sale);
        console.log(car);
    car
        .save()
        .then(() => {
            res.redirect('/');
        })
        .catch(err => console.log(err))
}

The save method is a model method/my first attempt at a transaction using the mysql2 npm package in the model:

        save() {
            db.getConnection()
                .then((db) => {
                    return db.query('START TRANSACTION');                    
                })
                .then(() => {
                    db.query('INSERT INTO cars (model_year, make, model, color, miles, transmission, layout, engine_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
                    [this.model_year, this.make, this.model, this.color,this.miles, this.transmission, this.layout, this.engine_type])
                })
                .then(() => {
                    db.query('INSERT INTO car_photos (car_photo_url) VALUES (?)',
                    [this.car_photo_url])
                })
                .then(() => {db.query('INSERT INTO car_price (car_price) VALUES (?)', [this.car_price])
                })
                .then(() => {db.query('INSERT INTO sales_status (sale_status, for_sale) VALUES (?, ?)', [this.sale_status, this.for_sale])
                })
                .then(() => {
                    return db.query('COMMIT');
                })
                .catch((error) => {
                    return db.query('ROLLBACK');
                })
        }

What's the problem?


Solution

  • The save() method should return a Promise, so you can call the .then and .catch in the chain.

    Please try something like:

    save() {
        return db.getConnection()
        ...
    }