0

I have:

var url = "mongodb+srv://exampleuser:53pr1WkCUkkOon0q@cluster0-zfo5z.mongodb.net/test?retryWrites=true&w=majority&useUnifiedTopology=true";

        MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db("rw_bewerbung");
            var query = { mc_uuid: uuid };
            dbo.collection("user_name_history").find(query).toArray(function(err, result) {
                if (err) throw(err);
                nameHistory = result[0].name_history;
                db.close();
            });
        });

And I want to get the variable nameHistory...how can I do this?

dizon27
  • 13
  • 3
  • You want to get it where? – Taplar May 18 '20 at 18:16
  • At the controller. At the same height as var url is. – dizon27 May 18 '20 at 18:18
  • I'm assuming that since the `connect()` is being given a callback method, that it is performing some form of asynchronous logic. If that is the case, then this quesiton falls in the same issue pattern as https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Taplar May 18 '20 at 18:19

1 Answers1

0

You can do this by converting your code into a promise:

  const bewerbung = async (url) => new Promise((resolve, rejected) => {
      MongoClient.connect(url, function(err, db) {
      if (err) {
        rejected(err);
      } else {
        const dbo = db.db("rw_bewerbung");
        const query = {mc_uuid: uuid};
        dbo
          .collection("user_name_history")
          .find(query)
          .toArray(function (err, result) {
            if (err) {
                rejected(err);
            } else {
                db.close();
                resolve(result[0]);
            }
          });
      }
});
}).catch(console.error);

const url = "todo...";
const res = await bewerbung(url);
const nameHistory = res.name_history;
console.info('nameHistory', nameHistory);

.

Marc
  • 1,836
  • 1
  • 10
  • 14