MongoDB objects are object Id of another document stored in the mongo database. Following is our sample mongo document we want to render in our React front end.
{ "_id": "5fef1f5087a69346300003a7", "title": "Title post", "content": "It is a good practice to keep styles for different pages in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?", "user": { "_id": "5fe4ab1e69b8d525c44ec293", "name": "admin", "createdAt": "2020-12-24T14:52:14.364Z", "updatedAt": "2021-01-01T13:12:59.084Z", "__v": 106 }, "createdAt": "2021-01-01T13:10:40.468Z", "updatedAt": "2021-01-01T13:10:41.907Z", "__v": 3 }
Our task is to render the user object and access its properties
For simplicity I skip the rest of the component code.
render() { return ( <div> <div className="card m-2 p-2"> <h3>{this.state.post.title}</h3> <div>{this.state.post.content} </div> <div> Posted By: {Object(this.state.post.user).name} </div> </div> </div> );
React recognize sub document as filed, not as an object. So we have to convert the user to Object ( the highlighted line)
So far we have succeeded to render the MongoDB object
Following React posts deserve good read
- How to clear all element in mongoose object array in Nodejs - How to clear elements in a mongodb object array
- Use dotenv to store configurations in Reactjs - use dotenv in Reactjs to store API base URL
- How to export multiple components in Reactjs - How to render export multiple components in React
- How to create ant row design for Reactjs - Quickly create a row design using Ant Design customize UI for React component
- Ant layout for Reactjs apps - How to create a app layout with Ant Design UI Kit in Reactjs
- How to render child components in Reactjs - How to render child components in React
- How to add element to mongoose object array in Nodejs - How to add element to a mongodb object array
- How to interact with input in Reactjs - How to handle state and event of input element in React apps
- How to render mongo object in Reactjs - How to render MongoDB object/ObjectId in React/MERN app
- How to render mongo document in Reactjs - How to render mongo document in react component