How to fix mongo object Type error in Reactjs


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

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.