lavnalla
lavnalla

Reputation: 31

MongoDB Find does not return anything

I would like to fetch data from MongoDB and post it in browser using node.js and express. My code is

However promise is not resolved and it called after the function returns My output is

PS C:\Websites\LearnDB> node FullStack Connected correctly to server After call[object Promise] undefined

Can someone tell me what I am doing wrong?

function getUsers (db) {
        return new Promise(function(resolve, reject) {
           db.collection("Users").find().toArray( function(err, docs) {
            if (err) {
              // Reject the Promise with an error
              return reject(err)
            }
      
            // Resolve (or fulfill) the promise with data
            var result = resolve(docs);

            console.log(result);

            return result;
          })
        })
      }

ourApp.post(`/Users`, function(req, res){

    db = client.db(dbName);
    console.log("Connected correctly to server");

    var docs = getUsers(db);
    
    console.log("After call" + docs);
     
    res.send(docs);
})

    

ourApp.listen(3000)

Upvotes: 0

Views: 66

Answers (1)

Manisha Jadhav
Manisha Jadhav

Reputation: 176

    async function getUsers (db) {
            return new Promise(function(resolve, reject) {
               await db.collection("Users").find().toArray( function(err, docs) {
                if (err) {
                  // Reject the Promise with an error
                  return reject(err)
                }
          
                // Resolve (or fulfill) the promise with data


                  console.log('Incoming result',docs);
                        resolve(docs);
              })
            })
          }
    
    ourApp.post(`/Users`, async function(req, res){
    
        var db = await client.db(dbName);
        console.log("Connected correctly to server");
    
        var docs = await getUsers(db);
        
        console.log("After call" + docs);
         
        res.send(docs);
    })
    

ourApp.listen(3000)

Add async await to all your database related operation. Everything will work fine like expected

Upvotes: 1

Related Questions