简体   繁体   English

如何在猫鼬中使用异步/等待

[英]How to use async/await with mongoose

In node.js I had code like following:在 node.js 中,我有如下代码:

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

Now i want to do it with async/await syntax.现在我想用 async/await 语法来做。 So i could start with var mcResult = await mongoose.connect(dbURI, dbOptions);所以我可以从var mcResult = await mongoose.connect(dbURI, dbOptions); , afaik it will wait for operation, until it ends with any result (much like calling C function read() or fread() in syncronous mode). , afaik 它将等待操作,直到它以任何结果结束(很像在同步模式下调用 C 函数read()fread() )。

But what should I write then?但是我应该怎么写呢? What does that return to the mcResult variable and how to check for an error or success?这会返回什么mcResult变量以及如何检查错误或成功? Basically I want a similar snippet, but written with proper async/await syntax.基本上我想要一个类似的片段,但用正确的 async/await 语法编写。

Also I wonder because I have auto reconnect, among dbOptions :我也想知道因为我有自动重新连接,在dbOptions

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

Would it "stuck" on await forever, in case if database connection is unavailble?如果数据库连接不可用,它会永远“卡住” await吗? I hope you can give me a clue on what would happen and how that would work.我希望你能给我一个关于会发生什么以及如何运作的线索。

Basically I want a similar snippet, but written with proper async/await syntax.基本上我想要一个类似的片段,但用正确的 async/await 语法编写。

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

Please try this, Below code has basics of db connectivity and a query :请试试这个,下面的代码包含数据库连接和查询的基础知识:

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

As we're talking about async/await then few things I wanted to mention - await definitely needs it's function to be declared as async - otherwise it would throw an error.当我们谈论async/await我想提几件事情await肯定需要将它的函数声明为async否则它会抛出错误。 And it's recommended to wrap async/await code inside try/catch block.并且建议将async/await代码包装在try/catch块中。

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

Lets assume the use of then() is prohibited, you can result to this...让我们假设禁止使用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)
    }
}

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

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