0

I'm trying to get data from my MongoDB database and return a new id for user creation through a function called create_user_id. I noticed the function returns undefined even though newID's value is numeric. Any idea why the function stops after the callback function of .toArray()?

const create_user_id = () => {
  let maxID = -1;
  let newID;
  users.find({}).toArray((err, results) => {
    if (err) {
      console.log(err)
    }
    else {
      results.forEach((item) => {
        if (item.id != null) {
          console.log("max id:", maxID)
          if (item.id > maxID) {
            maxID = item.id

          }
        }
      })
      newID = maxID + 1;
    }
  })
  console.log("doesnt reach this line", newID)
  return newID;
}
Itamar Ivri
  • 117
  • 6

0 Answers0