1

I'm not capturing the connect function to return in the getAllowedEmails function, when I do console.log in allowedEmails, it returns the emails correctly, but when I assign to the variable emails, it is returning empty. I think it's an async await problem but can't figured out.

static async getAllowedEmails() {
    
    var MongoClient = require("mongodb").MongoClient;
    
    //db url
    
    let emails = [];

    await MongoClient.connect(url, async function (err, client) {
      
      const db = client.db("data-admin");

      var myPromise = () => {
        return new Promise((resolve, reject) => {
          db.collection("users")
            .find({})
            .toArray(function (err, data) {
              err ? reject(err) : resolve(data);
            });
        });
      };
      var result = await myPromise();

      client.close();
      let allowedEmails = [];
      result.map((email) => allowedEmails.push(email.email));

      console.log(allowedEmails)

      emails = allowedEmails;
      
    });
    console.log(emails)
    
    return emails;

  }
1
  • 1
    It works, thanks man, think i lost myself using callback notation. Using fully async await is way better for me, the code turns much legible. Commented Nov 12, 2020 at 22:51

1 Answer 1

1

Your code has couple of issues, I have fixed few and enhanced it, given below is the basic code, try to test it and if everything works then enhance it as needed:

const MongoClient = require("mongodb").MongoClient;

async function getAllowedEmails() {
    let client;
    try {
        const allowedEmails = [];
        client = await MongoClient.connect(url);
        const db = client.db("data-admin");
        const result = await db.collection("users").find({}).toArray();
        result.map((email) => allowedEmails.push(email.email));
        console.log(allowedEmails)
        client.close();
        return allowedEmails;
    } catch (error) {
        (client) && client.close();
        console.log(error)
        throw error;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.