简体   繁体   中英

How to use async/await with mongoose

In node.js I had code like following:

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

Now i want to do it with async/await syntax. So i could start with 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).

But what should I write then? What does that return to the mcResult variable and how to check for an error or success? Basically I want a similar snippet, but written with proper async/await syntax.

Also I wonder because I have auto reconnect, among dbOptions :

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

Would it "stuck" on await forever, in case if database connection is unavailble? 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 () => {
  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. And it's recommended to wrap async/await code inside try/catch block.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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