0

In my code, I am sending a query to my Mongo database. The method findUser() shall return the response of this query. The query works fine, tested with console.log(users). The problem is the function returns null, it doesn't wait till the query got a response to return the var foundUser. How could I use await/async in this case in order to wait for the query response before returning anything ?

function findUser(username) { 
    foundUser = null
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology : true});
    client.connect(err => {
        const collection = client.db("YourCV").collection("Accounts");
        result = collection.findOne({username : username }, function(err, user) {
            console.log(user)
            if(user){
                foundUser = user
            }
        });
    });  
    return foundUser
};

console.log(user) outputs :

{
  _id: 601695084b28102500ae0015,
  username: 'jetlime',
  password: '$2b$10$EN5k/YKOMBgibqy62s0hGOX9MffHZtXkfsw0Du0j8QVS7mGab5FLi'
}

Many thanks

3 Answers 3

2

Update the code to the following:

async function findUser(username) {
    const client = await MongoClient.connect(url, { useNewUrlParser: true })
        .catch(err => { console.log(err); });

    if (!client) {
        return;
    }
    const collection = client.db("YourCV").collection("Accounts");
    const user = await collection.findOne({username : username });
    client.close(); // -> To be under finally clause.
    return user;
};

And call the function with await findUser(username);

Caution: The above of connecting to DB is not recommended. You are establishing a DB connection for every function call. This quickly leads to running out of connections on the DB side when you have a large number of requests.

Move the DB connection establishing part to a commonplace and re-use the connection.

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

Comments

1

See whatever you do, any operation you perform with your database, it returns promise, so write async keyword before the name of your function in line 1 and then await keyword before your query in line 6, it will then behave like synchronous call and every line will execute accordingly

Comments

1

As you said, you need to use async/await operators for asynchron methods.

You have two choices:

1)Implement callback method on findUser

  async function findUser(username, onUsersReady) {
    const client = new MongoClient(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }).connect();

    const collection = await client.db("YourCV").collection("Accounts");
    await collection.findOne({
      username: username
    }, function(err, user) {
      console.log(user)
      if (user) {
        foundUser = user
        onUsersReady(user);
      }
    });
  };

2)Use function to return results directly

async function findUser(username) {
  const client = await new MongoClient(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }).connect();

  const collection = await client.db("YourCV").collection("Accounts");
  const foundUser = await collection.findOne({
    username
  });
  return foundUser;
}

2 Comments

What's up with solution 1? Why would you mix async and callbacks? Number 2 is quite nice though.
@sandrooco I added async to connect 'mongo' and to get 'collection' smoothly

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.