0

I have been working with this function for a few days and I'm really stuck on why data never updates. What I would like is for data to update so I can use it but it just stays as undefined.

    var data; // This should update but it never does
    mclient.connect(async function (err) {
        // Find database by name then find user by their Discord ID
        const db = mclient.db(dbName);
        var cursor = db.collection('users').find({ userID: user.id });

        await cursor.forEach(element => {
            data = element;
            // When both are logged here, they return a JSON Object
        });
    });
    console.log(data) // Logs undefined
  • you get `undefined` because you are reading value of `data` variable before it is initialized. `data` variable is initialized asynchronously – Yousaf May 25 '20 at 12:05

0 Answers0