Search code examples
node.jsmongodbsynchronous

Unable to call the functions in synchronous way using node.js and mongodb


I am trying to call some function in synchronously using node.js but as per my code its not happening. I am explaining my code below.

viewDraggedFileContent = async(req, res) => {

    try{
        let id = req.params.id;
        if(!id) {
            responseObj = {
                status: 'error',
                msg: 'Please send the mongo id to fetch the file content.',
                body: {}
            };
            res.send(responseObj);
        }else{
            let response = await findOne(id, 'useCaseFile');
            console.log('res', response);
            if(response['status'] === 0) {
                responseObj = {
                    status: 'error',
                    msg: `Error occurred`,
                    body: response['data']
                };
                res.send(responseObj);
            }else{
                const resObj = [{
                    fileData: response.data.fileData,
                    _id: response['data']['_id']
                }]
                responseObj = {
                    status: 'success',
                    msg: `Fetched data successfully`,
                    body: resObj
                };
                res.send(responseObj);
            }
        }
    }catch(error) {
        console.log('Error::', error);
    }
}

/**
 * 1- Method to fetch single record from mongoDB as per _id.
 */

findOne = async (id, collName) => {
    try{
        let mongoID = new ObjectId(id);
        MongoClient.connect(dbUrl, dbOptions).then(function (client) {
            let connObj = client.db(dbName);
            connObj.collection(collName).findOne({ _id: mongoID }, function (error, doc) {
                if (error) {
                    client.close();
                    return {
                        status: 0,
                        data: error
                    };
                } else {
                    client.close();
                    return {
                        status: 1,
                        data: doc
                    };
                }
            })
        })
    }catch(error){
        console.log('Error while fetching single record::', error);
    }
}

Here I am calling findOne function from viewDraggedFileContent function. My objective is once the required data will return from findOne function then console.log('res', response); should execute but as per my code console.log('res', response); is executing before getting response from findOne. I have also used async---await but still its running asynchronously. Here I need after getting response from findOne function then the console message should display.


Solution

  • You can use async/await in the findOne function

    async function findOne(id, collName) {
      const client = await MongoClient.connect(url, {
        useUnifiedTopology: true,
      }).catch((err) => {
        console.log("Error while connecting to db", err);
      });
      if (client) {
        try {
          let mongoID = new ObjectId(id);
          let connObj = client.db(dbName);
          let doc = await connObj.collection(collName).findOne({ _id: mongoID });
          return {
            status: 1,
            data: doc,
          };
        } catch (error) {
          console.log("Error while fetching single record::", error);
          return {
            status: 0,
            data: error,
          };
        } finally {
          client.close();
        }
      }
    }