1

I want to access the data from my local mongoDB and I want to search for all keys without making a state{} wherein I will have to pre-define what kind of keys are present in the database. Now although this problem has been answered numerous times by different people , most of them have the data in the following format ( it is a random example):

{
  "object": {
    "name": "Pluralsight",
    "number": 1,
    "address": "India",
    "website": "https://www.pluralsight.com/"
  }
}

or like this:

{
"String":"EternalSunsetOfCloudedMind",
"Rating": 2
}

In the above two examples we can easily use the function : <p>Name: {sampleJSON.object.name}</p> or <p>String : {sampleJSON.string}</p>

But what if the database looked like this:

[{"_id":"60d1b5493b470b3884325872","Title":"CatManBegins" ,"Image":"https://m.media-amazon.com/images/catmanbegins.jpg","Rating":9},
  {"_id":"60d1b5d0b25e04287318a072", "Title":"Cabdriver","Image":"https://m.media-amazon.com/images/cabdriver.jpg"},
  {"_id":"60d314a981ecb624dc6966a2","Title":"Pulpnonfiction" ,"Image":"https://m.media-amazon.com/images/pulpnonfiction.jpg","Review":{"AlphaReview":"WOW!","BetaReview":"Okay nice","GamaReview":"Hmm"}},
  {"_id":"60d32406affa146b4b1428a2", "Title":"DoctorNormal","Category":"Marvellous Movies"},
  {"_id":"60d5cfc6326f1c336d3478e2", "Title":"GameOfKingdoms","BudgetInDollars":100000}]

How can I do the same in this kind of database?

My current knowledge and progress: Till now I have been able to fetch the data from MongoDB to the server-side, from which I have been able to send the JSON to the client-side after parsing it using the following code:

Server.js

app.get('/run-query',async(req,res)=>{
MongoClient.connect('mongodb://localhost:27017',{useNewUrlParser: true, useUnifiedTopology: true}, function(err,db){
    if(err) throw err;
    var dbo = db.db("MyDatabaseName");
    dbo.collection("MyCollectionName").find({}).toArray(function(err,result){
        if(err) throw err;
        res.json(result);
        db.close();
    });
});

})

Client/src/App.js

function App() {
  const [data, setData]= useState(null);
  useEffect(()=>{
    fetch('/run-query')
      .then ((res)=>res.json())
      .then (setData)
      .catch(console.error)
  }, []);
 
  return (
    <div>
      <h1>All results </h1>
      <div class="box">
        <p>{!data ? "loading..." : JSON.stringify(data)}</p> 

      </div>
    </div>     
  );
}

1 Answer 1

2

When you want to display an array, usually you’ll want to map each item in the array to a React element.

To get all property names and values of a JavaScript object, you can use the Object.entries() function.

Putting these two together:

// maps each object in the array to an unordered list of key/value pairs
const dataItemToKeyValues = (item) => {
  const entries = Object.entries(item);
  const listItems = entries.map(([key, value]) => (
    <li>
      {key}: {value}
    </li>
  ));
  return <ul>{listItems}</ul>;
};

return (
  <div>
    {!data ? (
      "Loading"
    ) : (
      <ul>
        {data.map((item) => (
          <li>{dataItemToKeyValues(item)}</li>
        ))}
      </ul>
    )}
  </div>
);

The React documentation has a section on lists that has more information.

Sign up to request clarification or add additional context in comments.

4 Comments

I've updated my answer to display all the properties of each object in the list.
Hi Stephen! Thank you for that solution, it nearly solved my issue but there was an error. It seems that it is giving an error because it is unable to crack the subdocuments. Here is the exact error: Uncaught Error: Objects are not valid as a React child( found: object with keys {AlphaReview,BetaReview,GamaReview}). If you meant to render a collection of childer, use an array instead.
Some of your documents have properties with objects as their values (in your sample data, it's the "Review" property). You'll need to write additional code to detect and handle this case, because, as the error message says, React cannot display arbitrary objects. If this is just for prototyping, you could use JSON.stringify(value) on all values, but if you want a proper display you're going to have to write code to handle it.
Yes, my aim is to even get the key-value pairs inside the subdocument. So simple JSON.strigify won't work. I will look into this part. In case you might know any source from which I would be able to learn it then do let me know :D Thanks for the help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.