Search code examples
javascriptnode.jsreactjsmongodbmongoose

Trying to get data from my database using mongoose but instead it returns the query


I am trying to send data from express to react using mongoose when I log collection.find(); instead of returning every piece of data in my database it returns the query https://pastebin.com/2ShSuPp4

Code: https://pastebin.com/84XAvC0E when I go to the react app it gives me a 404 error

I didn't write my code in here because for some reason it doesnt recognise javascript when i use the `` brackets


Solution

  • app.post("/table", function(req, res) {
      let response = collection.find();
      console.log(response);
      res.send(response);
    });
    

    The .find() method on any model is asynchronous in nature and actually returns a promise to the query. You need to await on the query to get the actual data from the database. And hence, the response variable contains the promise.

    You need to use either async/await syntax or .then().catch() syntax to get hold of the data received from the database server.

    app.post("/table", async function(req, res) {
      try{
        let response = await collection.find();
        console.log(response);
        res.send(response);
      }catch(e){
        // your error handling logic
      }
    });
    

    OR using .then().catch()

    app.post("/table", function(req, res) {
      collection.find()
        .then((response)={
          console.log(response);
          res.send(response);
        })
        .catch((e)=>{
          // your error handling logic
        })    
    });