【问题标题】:How to use async/await with mongoose如何在 mongoose 中使用 async/await
【发布时间】:2019-07-20 07:08:29
【问题描述】:

在 node.js 中我有如下代码:

mongoose.connect(dbURI, dbOptions)
.then(() => {
        console.log("ok");
    },
    err => { 
        console.log('error: '+ err)
    }
);

现在我想用 async/await 语法来做。所以我可以从 var mcResult = await mongoose.connect(dbURI, dbOptions); 开始,afaik 它将等待操作,直到它以任何结果结束(很像在同步模式下调用 C 函数 read()fread())。

但是那我应该写什么呢?什么返回到mcResult 变量以及如何检查错误或成功?基本上我想要一个类似的 sn-p,但使用正确的 async/await 语法编写。

我也想知道,因为我有自动重新连接,在dbOptions

dbOptions: {
  autoReconnect: true,
  reconnectTries: 999999999,
  reconnectInterval: 3000
}

如果数据库连接不可用,它会永远“卡在”await 上吗?我希望你能给我一个线索,让我知道会发生什么以及它是如何工作的。

【问题讨论】:

    标签: node.js asynchronous mongoose error-handling async-await


    【解决方案1】:

    基本上我想要一个类似的 sn-p,但使用正确的 async/await 语法编写。

    (async () => {
      try {
        await mongoose.connect(dbURI, dbOptions)
      } catch (err) {
        console.log('error: ' + err)
      }
    })()
    

    【讨论】:

    【解决方案2】:

    请试试这个,下面的代码有基本的数据库连接和查询:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    let url = 'mongodb://localhost:27017/test';
    
    const usersSchema = new Schema({
        any: {}
    }, {
        strict: false
    });
    
    const Users = mongoose.model('users', usersSchema, 'users');
    
    /** We've created schema as in mongoose you need schemas for your collections to do operations on them */
    
    const dbConnect = async () => {
        let db = null;
        try {
            /** In real-time you'll split DB connection(into another file) away from DB calls */
            await mongoose.connect(url, { useNewUrlParser: true }); // await on a step makes process to wait until it's done/ err'd out.
            db = mongoose.connection;
    
            let dbResp = await Users.find({}).lean(); /** Gets all documents out of users collection. 
                                       Using .lean() to convert MongoDB documents to raw Js objects for accessing further. */
    
            db.close(); // Needs to close connection, In general you don't close & re-create often. But needed for test scripts - You might use connection pooling in real-time. 
            return dbResp;
        } catch (err) {
            (db) && db.close(); /** Needs to close connection -
                       Only if mongoose.connect() is success & fails after it, as db connection is established by then. */
    
            console.log('Error at dbConnect ::', err)
            throw err;
        }
    }
    
    dbConnect().then(res => console.log('Printing at callee ::', res)).catch(err => console.log('Err at Call ::', err));
    

    当我们谈论 async/await 时,我想提几件事 - await 肯定需要将其函数声明为 async - 否则会引发错误。并且建议将async/await 代码包裹在try/catch 块内。

    【讨论】:

      【解决方案3】:
      const connectDb = async () => {
          await mongoose.connect(dbUri, dbOptions).then(
              () => {
                  console.info(`Connected to database`)
              },
              error => {
                  console.error(`Connection error: ${error.stack}`)
                  process.exit(1)
              }
          )
      }
      
      connectDb().catch(error => console.error(error))
      

      假设禁止使用then(),您可能会导致...

      const connectDb = async () => {
          try {
              await mongoose.connect(dbConfig.url, dbConfigOptions)
      
              console.info(`Connected to database on Worker process: ${process.pid}`)
          } catch (error) {
              console.error(`Connection error: ${error.stack} on Worker process: ${process.pid}`)
              process.exit(1)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-28
        • 2022-11-18
        • 2019-04-15
        • 1970-01-01
        • 1970-01-01
        • 2023-01-05
        • 2018-03-09
        • 2019-04-17
        • 1970-01-01
        相关资源
        最近更新 更多