如何在mongoose中使用async/await

3
在node.js中,我有以下代码:
mongoose.connect(dbURI, dbOptions)
.then(() => {
        console.log("ok");
    },
    err => { 
        console.log('error: '+ err)
    }
);

现在我想使用async/await语法来完成它。所以我可以开始使用var mcResult = await mongoose.connect(dbURI, dbOptions);,据我所知,它会等待操作,直到以任何结果结束(就像在同步模式下调用C函数read()fread()一样)。
但是我应该写什么呢?那返回给mcResult变量的是什么,如何检查错误或成功?基本上,我想要一个类似的片段,但是用适当的async/await语法编写。
另外,我想知道,因为我有自动重新连接功能,在dbOptions中:
dbOptions: {
  autoReconnect: true,
  reconnectTries: 999999999,
  reconnectInterval: 3000
}

如果数据库连接不可用,await会一直卡住吗?希望您能给我一个提示,告诉我会发生什么以及如何解决。

3个回答

14
基本上,我想要一个类似的代码片段,但使用适当的async/await语法编写。
(async () => {
  try {
    await mongoose.connect(dbURI, dbOptions)
  } catch (err) {
    console.log('error: ' + err)
  }
})()

@xakepp35 是的。如果你跟随Connection.prototype.openUri的逻辑,你会发现它最终会被拒绝。 - john-goldsmith

6

请尝试这个,下面的代码包含了数据库连接和查询的基础:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接