Question

TypeError: Cannot read properties of undefined when accessing nested object

78776f7b-649f-4576-b6e5-54537e674b98

I keep getting this error in my Node.js app:

TypeError: Cannot read properties of undefined (reading "name")

My code looks like:

const user = await db.findOne({ id: userId })
console.log(user.profile.name) // crashes here

The user exists in the database but sometimes this crashes. What is happening and how do I safely access nested properties?