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
}
In the above document we want to render the user object and the following code will cause an type error
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: {(this.state.post.user).name}
</div>
</div>
</div>
);
TypeError: Cannot read property ‘name’ of undefined
Error Fix
React recognize sub document as filed, not as an object.To fix the error we have to convert the user to Object as follows.
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>
);
Following React posts may help you
- 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
- How to render list of mongo objects in React component - How to render list of mongo objects in Reactjs
- How to place custom route links in Reactjs component - How to place custom links to routes/page in Reactjs
- How to fix mongo object Type error in Reactjs - How to fix TypeError/undefined in React - MERN application
- How to create multi page app with Reactjs - How to create a multi routed app with Reactjs app
- How to make GET API request in Reactjs - How to make GET API call in Reactjs
- How to make POST API request in Reactjs - How to make POST API call in Reactjs
- Create a login Form component in Reactjs - How to create a login form component using refs,props and CSS in Reactjs
Like this:
Like Loading...