Learn Node SQLite

Using db.each()

While learning JavaScript, you likely learned about the powerful method .forEach() that allows us to process every element in an array separately. Now we will use a similar method that will enable us to process every row returned from a database query.

db.each("SELECT * FROM Dog WHERE breed = 'Labrador'", 
  (error, row) => {
    // This gets called for every row our query returns
    console.log(`${row.name} is a good dog`);
  (error, numberOfRows) => {
    // This gets called after each of our rows have been processed
    console.log(`There were ${numberOfRows} good dogs`);

In the code above we SELECT all the Labrador dogs from our Dog database. We offer affirmation to each of the animals individually and then announce how many received this praise in sum.

db.each() takes a query and a callback function that it performs on each row returned from the query. This is a useful technique for transforming or updating rows. This is also useful for memory management — we only have to look at one row at a time instead of trying to process every returned row at the same time. db.each() additionally takes an optional second callback function, which will be called when all of the queries are completed and processed.

Community Forums
Get help and ask questions in the Codecademy Forums
Report a Bug
If you see a bug or any other issue with this page, please report it here.