繁体   English   中英

如何在 Nodejs 中使用 Async/Await 连接到 MongoDB?

[英]How to connect to MongoDB with Async/Await in Nodejs?

我有一个带有静态方法的 Connection 类,它允许我为 MongoDB 连接创建一个单例类型对象。 将 Async 与 Await 一起使用,在我的其余代码执行之前,我永远无法连接到“触发”。

使用传统的 Promise / .then 这个 Connection 类可以工作。 使用最新的 Nodejs 版本和 MongoDB 版本。

static connectDb() {
    //If MongoDB is already connected, return db object
    if (this.dbClient) {
      //const currDbClient = Promise.resolve(this.dbClient);
      console.log(`MongoDB already connected!`);
      return this.dbClient;
    }
    //Otherwise connect
    else {
      async () => {
        try {
          const newDbClient = await MongoClient.connect(this.url, this.options);
          console.log(`DB is connected? ${newDbClient.isConnected()}`);
          ConnectMeCore.dbClient = newDbClient;
          return newDbClient;
        } catch (error) {
          console.error(`MongoDB connection failed with > ${error}`);
        }
      };
    }
  }

我希望等待“等待”数据库连接,或者至少解决承诺。

感谢@JaromandaX帮助您找到答案!

一旦发生数据库连接,调用代码可以使用Promise.then执行代码。

DbConnection.connectDb().then(() => {
      console.log("Is it connected? " + DbConnection.isConnected());
      //Do CRUD
      DbConnection.closeDb();
    });

您可以将此方法(作为“连接”类的一部分)导入任何需要建立数据库连接的类。 用于数据库连接的单例。 工作方法片段如下。

  static async connectDb() {
    //If MongoDB is already connected, return db object
    if (this.dbClient) {
      const currDbClient = Promise.resolve(this.dbClient);
      console.log(`MongoDB already connected!`);
      return currDbClient;
    }
    //Otherwise connect using 'await', the whole methos is async
    else {
      try {
        const newDbClient = await MongoClient.connect(this.url, this.options);
        console.log(`DB is connected? ${newDbClient.isConnected()}`);
        this.dbClient = newDbClient;
        return newDbClient;
      } catch (error) {
        console.error(`MongoDB connection failed with > ${error}`);
        throw error;
      }
    }
  }
let MongoClient = require('mongodb').MongoClient;
const connectionString = 'mongodb://localhost:27017';

    (async () => {
        let client = await MongoClient.connect(connectionString,
            { useNewUrlParser: true });

        let db = client.db('dbName');
        try {
           const res = await db.collection("collectionName").updateOne({ 
               "someKey": someValue
           }, { $set: someObj }, { upsert: true });

           console.log(`res => ${JSON.stringify(res)}`);
        }
        finally {
            client.close();
        }
    })()
        .catch(err => console.error(err));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM