0

I am using node-cron to update mysql database every minute, node-cron is working fine (as I checked it by logging some data in the console) but its not updating the database. What am I missing?

const cron = require("node-cron");
const db = require("../util/database");

cron.schedule(`* * * * *`, () => {
  db.getConnection((error, connection) => {
    if (!error) {
      connection.query(
        "SELECT some_field from users",
        (err, users) => {
          if (!err) {
            for(let i = 0; i < users.length; i++){
              let some_var = 1;
              let updated_field = users[i].some_field + some_var;
              connection.query(
                "UPDATE users SET some_field= ? WHERE users.id = ?",
                [updated_field, users[i].id],
                (errs, rows) => {
                  if(!errs){
                    // console.log(updated_field);
                  }
                }
              );
            }
            connection.release();
          }
        }
      );
    }
  });
})
Aimsat
  • 338
  • 4
  • 10
  • `WHERE users.id = ? ` or `WHERE id = ?` ? – ikhvjs Feb 15 '22 at 14:22
  • tried id = ? too. Still not updating. – Aimsat Feb 15 '22 at 14:25
  • Did you try the SQL in DB directly instead of node.js? – ikhvjs Feb 15 '22 at 14:28
  • Yes. It works directly. Also I updated the db in similar manner without using cron. That also works – Aimsat Feb 15 '22 at 14:43
  • what db library do you use? I know your issue. You execute `connection.release();` too early before any update finish. – ikhvjs Feb 15 '22 at 14:50
  • Where should I release the connection? I am using mysql^2.18.1 – Aimsat Feb 15 '22 at 15:06
  • Do you know [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) in js? you need to implement promise in the callback and await all the update finish. [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – ikhvjs Feb 15 '22 at 15:49

0 Answers0