Tirafesi
Tirafesi

Reputation: 1469

This object is empty inside callback function of run() method

I'm writing a server using NodeJS, Express and SQLite in order to provice RESTful services.

I want to create an endpoint for adding a new user to the database. The endpoint receives a POST request with the parameters username and password, and responds with the id of the newly created user.

According to the node-sqlite3 package documentation, when the run method succeeds, the this object inside the callback function contains the properties lastID and changes.

My problem is that, even though the run method succeeds and the new user is successfully inserted into the database, the this object is empty.

What am I doing wrong? How can I access this.lastID?

app.post('/users', (req, res) => {
    const {
        username,
        password
    } = req.body;

    db.get(
        `SELECT id
        FROM Users
        WHERE username = ?`,
        [username],
        (err, row) => {
            if (err) {
                console.error(err);
                return res.sendStatus(500);
            } else if (row) {
                return res.status(400).send('Username already exist.');
            }

            db.run(
                `INSERT INTO Users (username, password)
                VALUES (?, ?)`,
                [username, password],
                (err) => {
                    if (err) {
                        console.error(err);
                        return res.sendStatus(500);
                    }
                    console.log(this); // prints {} to the console
                    res.send(this.lastID); // response body is empty
                }
            );
        }
    );
});

Upvotes: 0

Views: 131

Answers (1)

dr_barto
dr_barto

Reputation: 6075

Try using an old-school function instead of an arrow function for your callback. I think with arrow functions this cannot be bound to a value.

Upvotes: 2

Related Questions