Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs node-sqlite3 run callback not working

Tags:

node.js

sqlite

I am trying to perform a delete of a row in sqlite db using nodejs and node-sqlite3 package.

When I run the delete command, and manually check the entries, I can see that the query successfully deleted that row but I cant seem to write the code that confirms this.

This is the query

db.run("DELETE FROM Table1 WHERE id=? AND username=?", [id, user], function(error) {
console.log(error);
});

Regardless of a wrong or right input, it outputs null to the console. If the right details are given, it deletes it and prints null, if wrong id and user are given, it still prints null.

Any ideas on what might be wrong?

Thanks

like image 601
Kartik Avatar asked Dec 20 '22 23:12

Kartik


1 Answers

To my prevoius question, the problem was that I've used fat arrow for callback declaration. From javascript documentation I've discovered that in arrow function (fat arrow ), this has lexical scope and so this result undefined and not valued as in library documentation said. Using otherwise anonimous function, this is bounded in dynamic scope and so this.changes is valued.

Now, with code as below, is ok:

var sql = 'update recipes set stars = stars + 1 where id = ?';

db.run(sql,
    [
    1 // id = 1 execute update - if id = 11111 do nothing
    ], function(err) {
        if(err)
            throw err;

        console.log("VALUE CHANGES: " + this.changes + " - " + util.inspect(this, { showHidden: false, depth: null }));

        if(this.changes == 1)
            console.log("WORK DONE");
        else
            console.log("NOTHING DONE");

    });

Here more explanations: https://github.com/mapbox/node-sqlite3/issues/606

like image 140
Massimo Cappellano Avatar answered Dec 24 '22 01:12

Massimo Cappellano