I'm not able to access the populated fields of mongoose objects. I want to output it in my page.
Example:
"console.log(booking.assignedUser.first)" gives me back:
TypeError: Cannot read properties of undefined (reading 'first')
But from what I can tell, this should be working. The field is clearly there.
In my jsx file:
console.log(booking.assignedUser)
{
etc etc
assignedUser: { _id: new ObjectId("62f068b068802d58c8d35442"), first: 'driver' },
etc etc
}
So why I can access booking.assignedUser and it shows me the data, but booking.assignedUser.first doesn't work?
CodePudding user response:
Because these values are being populated from the DB, I guess they aren't loading fast enough so it's giving me this error.
If I check to make sure the value exists first, then use it, it's working.
I'm working with a lot of this type of data in my app, so instead of outputting the jsx directly in the react object, I'm using a function to return it all for me which I pass in the db data.
using a ternary at the beginning of the output within the React component was not good enough, for example.
{ data ?
<Form>
<SomeStuffHere>
<SomeMoreStuffHere>
<Form.Control> {data.something} </Form.Control>
</Form>
: '' }
This was not good enough. It would still error out. I had to place the ternary immediately on the field in order for it to work.
Doing this for every single field would be a pain in the ass, so putting it into a function first seems to work better.
CodePudding user response:
Probably , you are trying to achieve data's populates when data didn't set yet. Need to be sure data is set already.
You can use it like ;
booking.assignedUser && console.log(booking.assignedUser.first)
If the page can't view components due to data is empty, need to use this condition beginning of view component.
data.length > 0 && ...</Component/>