function returning nothing in mongodb query

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;

  }

Upvotes: 1

Views: 99

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

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;
    }
}

Upvotes: 1

Related Questions