首页 > 解决方案 > 如何从 MongoDB 函数中的函数获取变量?

问题描述

我有:

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

我想得到变量 nameHistory ......我该怎么做?

标签: javascriptnode.jsmongodbexpress

解决方案


您可以通过将代码转换为承诺来做到这一点:

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

.


推荐阅读