0

I'm having an issue with getting data out of a MongoDB collection and return it into an array in my code in NodeJS.

The code so far returns a promise, that I don't fully know how to handle.

Any help would be appreciated.

async function loadData() {

    try {
        // Connect to the MongoDB cluster
        console.log('Attempting to connect to DB')
        client.connect(async err => {
            const collection = client.db("db").collection("collection");
            await collection.find({}).toArray().then((data) => {

            //Getting stumped as the data gets returned as a promise and does not get added to an array

            }
            );

        client.close();
        console.log('Closed DB connection');

        });
    } catch (e) {
    console.error(e);
    }

2 Answers 2

1

You are using promises wrong as well as async await. The purpose of async/await is to avoid using the .then function. Pick one, use either or.

using callback method:

collection.find({}).toArray().then((data) => {
  console.log(data);
}, err => {
  // this gets called if there is an error only
  console.log(err);
});

or with async/await:

try {
  const data = await collection.find({}).toArray();
}
catch(err) {
  console.log(err);
}

note that if you choose to use async/await, the containing function must be marked async, which you're already doing. This is not required if you use the above callback method.

Sign up to request clarification or add additional context in comments.

Comments

0
Don't execute the Promise inside the loadData function 


 function loadData() {

    try {
        // Connect to the MongoDB cluster
        console.log('Attempting to connect to DB')
        client.connect(async err => {
            const collection = client.db("db").collection("collection");
            return collection.find({})
            );

        client.close();
        console.log('Closed DB connection');

        });
    } catch (e) {
    console.error(e);
    }

And mak a call to get your Data

try {
  const your_Array = await loadData().toArray();
}
catch(err) {
  console.log(err);
}

And for the MongoDB connection, I think you're doing it wrong , Follow this gist

2 Comments

Thank you! :) However, I have to note that I'm not using mongoose. Instead, I'm using the official MongoDB connector
Using an ORM will provide for you more functionality than the official connector !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.