Skip to content Skip to sidebar Skip to footer

Nodejs Async Call Of Mongoclient Getdata Routine

The code below is a mix of https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp and https://stackoverflow.com/questions/49982058/how-to-call-an-async-function#:~:text=Putting%2

Solution 1:

The thing is getLanguageTranslationData should return a promise so that you can use it as a promise in your handler, but in your case, call to getLanguageTranslationData will return undefined as all the code inside this function will execute asynchronously due to nodejs non-blocking nature.

So what you can do is return promise from your getLanguageTranslationData function like this.

functiongetLanguageTranslationData(fromLanguage, toLanguage) {
    const databaseUrl = "mongodb://localhost:27017"const databaseName = 'MyCompanyPOC'returnnewPromise((resolve, reject)=>{
        mongoClient.connect(databaseUrl, function(err, conn) {
            if (err) reject(err); 
            else{
                const collectionName = "Phrases";
                var dbo = conn.db(databaseName)
                var query = 
                        { $and: 
                               [ {masterLanguage: fromLanguage},
                                 {localizedLanguage: toLanguage} 
                               ]
                        }
                dbo.collection(collectionName).find(query).toArray( 
                     function(err, result) {
                          if (err) reject(err); 
                          elseresolve(result);    
                   }) 
            }
           
        }) 
    }) 
}

and then use await in your handler to use that promise returned

app.get("/api/gettranslations/:fromLanguage/:toLanguage", 
  asyncfunction(req, res) {
      try{
        let arrayResult = await getLanguageTranslationData(req.params.fromLanguage, req.params.toLanguage);
        res.status(200).json(arrayResult)
      }catch(err){
        // return error
      }
}) 

The above code will give you the gist of what you need to do, actual code may vary according to your needs.

You can refer async-await from here

Solution 2:

I got it working in this way, based on this example: Node.js, Mongo find and return data

@Namar's answer is probably correct too, but I was testing this the same time he posted. As the StackOverflow question/answer above notes, the up-to-date versions of MongoClient have support for promises. That post also shows how to put in a separate module, which is something I will probably do later this week.

functiongetLanguageTranslationData(fromLanguage, toLanguage) {
    console.log("Started getLanguageTranslationData")
    const databaseUrl = "mongodb://localhost:27017"const databaseName = 'ShedCompanyPOC'return mongoClient.connect(databaseUrl)
        .then(function(conn) {
            var collectionName = "UploadedDataeFromExcel";
            var dbo = conn.db(databaseName)
            var query = 
                    { $and: 
                           [ {masterLanguage: fromLanguage},
                             {localizedLanguage: toLanguage} 
                           ]
                    }
            console.log("query=" + JSON.stringify(query)); 
            console.log("about to retrieve data"); 
            var collection = dbo.collection(collectionName)
            return collection.find(query).toArray(); 
        }).then(function(result) {
              console.log("Back from mongoDB.find()")
              console.log(JSON.stringify(result))
              //conn.close()return result
        }); 
    }



app.get("/api/gettranslations/:fromLanguage/:toLanguage", 
        asyncfunction(req, res) {
  console.log("Backend: /api/gettranslations method started: " + 
     " fromLanguage=" + req.params.fromLanguage + 
     " toLanguage=" + req.params.toLanguage)
  
  getLanguageTranslationData(
                             req.params.fromLanguage, 
                             req.params.toLanguage)
        .then(function(arrayResult) {
           console.log("got arrayResult back from getLanguageTranslationData")
           res.status(200).json(arrayResult)
           console.log("Backend: End of /api/gettranslations process")
         }, function(err) {
             console.log("The promise was rejected", err, err.stack)
         })
}) 

Post a Comment for "Nodejs Async Call Of Mongoclient Getdata Routine"