Home > Blockchain >  MongoDB Find does not return anything
MongoDB Find does not return anything

Time:12-31

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)

CodePudding user response:

To fetch data from a MongoDB database and display it in a web browser using Node.js and Express, you will need to follow these steps:

  1. Install the required dependencies:
  • Install MongoDB and Node.js on your system.
  • Create a new Node.js project and install the following dependencies:
  • express: A fast, unopinionated, minimalist web framework for Node.js.
  • mongodb: A MongoDB driver for Node.js.
  1. Connect to the MongoDB database:
  • Import the mongodb library and create a client to connect to the MongoDB server.

  • Use the client.connect() method to establish a connection to the database.

    const MongoClient = require('mongodb').MongoClient;
    const uri = "mongodb srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
    const client = new MongoClient(uri, { useNewUrlParser: true });
    client.connect(err => {
    // Connected successfully
    const collection = client.db("test").collection("devices");
    // perform actions on the collection object
     client.close();
    });
    
  1. Define a route to fetch the data:
  • Define a route in your Express app that will be responsible for fetching the data from the database.

  • Use the collection.find() method to retrieve the documents from the collection, and the toArray() method to convert the results to an array.

    app.get('/api/data', (req, res) => {
    connectToDb()
      .then(collection => {
     // Fetch the data from the collection
    return new Promise((resolve, reject) => {
      collection.find({}).toArray((err, docs) => {
        if (err) {
          reject(err);
        } else {
          resolve(docs);
        }
      });
     });
    })
    .then(docs => {
     // Send the data as a response
     res.send(docs);
    })
    .catch(err => {
      // Handle errors
      console.log(err);
      res.sendStatus(500);
    });
    

});

  1. Display the data in the browser:
  • In your HTML file, use JavaScript to make a request to the route defined in step 3 and display the data in the browser.

    <body>
    <div id="data">
      <!-- Data will be displayed here -->
    </div>
    <script>
    // Make a request to the /api/data route
    fetch('/api/data')
      .then(response => response.json())
      .then(data => {
        // Iterate over the data and append the values to the DOM
        data.forEach(item => {
          const div = document.createElement('div');
          div.textContent = item.value;
          document.getElementById('data').appendChild(div);
        });
      })
      .catch(err => {
        // Handle errors
        console.log(err);
      });
    </script>
    </body>
    

CodePudding user response:

    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

  • Related