Willem van der Veen
Willem van der Veen

Reputation: 36580

Mongodb async await with express

Developing an app with MongoDB and express.js using the Node.js MongoDB driver(using this driver instead of Mongoose for performance). I want use asynchronous function as a more elegant solution for managing my asynchronous code.

I know that if we have no callbacks on Mongo.client.connect(url) we return a promise like this:

app.get('/', (req, res ,next) => {

    let db = MongoClient.connect('mongodb://localhost:27017/playground');
    db
    .then(() => console.log('success'))
    .catch(() => console.log('failure'));

next();
});

When we add the async keyword and do also an insert function we now have this:

app.get('/', async (req, res ,next) => {

        try{
            var db = await MongoClient.connect('mongodb://localhost:27017/playground');
            let myobj = { name: "Company Inc", address: "Park Lane 38" };
            await db.db("mydb").collection("customers").insertOne(myobj);
        }catch(err){
            console.log(err);
        }finally{
            db.close();
        } 

    next();
});

Question

If any promise is rejected in the try block, will the code in the catch block be executed?

Upvotes: 0

Views: 2651

Answers (1)

Bergi
Bergi

Reputation: 664297

Does every database operation method (e.g. findOne, InsertMany, createCollection) of MongoDB driver return a promise when you have no callback?

Yes. This behaviour can be found in the documentation of all these methods.

If any promise is rejected in the try block, will the code in the catch block be executed?

Only if the rejected promise has been awaited in the try block.

Upvotes: 4

Related Questions