soubhagya pradhan
soubhagya pradhan

Reputation: 547

How to use async and await with Express and MongoDB

    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    const mongodb = require('mongodb');

    const app = express();
    app.use(cors())
    app.use(bodyParser.json());


    const MongoClient = mongodb.MongoClient;
    const url = "mongodb://localhost:27017/recart";


    app.post("/register" , (req, res) => {
        const { displayName, email, password } = req.body;
        if (!email || !displayName || !password) {
            return {code: 400, msg: "incorrect form submission"}
        }
        let insertedid = null
        MongoClient.connect(url, (err, db) => {
            if (err) throw err;
            var dbo = db.db("recart");
            var myobj = { displayName: displayName, email: email, password: password };
            dbo.collection("customers").insertOne(myobj)
            .then(res => {
                insertedid = res.insertedId
            })
        });
        res.json({id: insertedid})
    })

    app.listen(process.env.PORT || 3000, ()=> {
        console.log(`App is running on port 3000`);
    })

Here, I am storing data inside db and sending the last inserted id to the frontend.

However, id is returning null.

How can I use async and await to solve this issue?

Upvotes: 2

Views: 153

Answers (1)

Afrida Anzum
Afrida Anzum

Reputation: 573

You can modify your post function using async await like this:

app.post("/register", async (req, res) => {
     const { displayName, email, password } = req.body;
       if (!email || !displayName || !password) {
           return {code: 400, msg: "incorrect form submission"}
       }
       let insertedid = null ;
       MongoClient.connect(url,{ useNewUrlParser: true }, async (err, db) => {
           if (err) throw err;
           var dbo = db.db("recart");
           var myobj = { displayName: displayName, email: email, password: password };
           var result = await dbo.collection("customers").insertOne(myobj);
           insertedid = result.insertedId;
           res.json({ id:  insertedid})
     });
})

Upvotes: 2

Related Questions