Answer
The error occurs because `user` is `undefined` in some cases, likely when the query `db.findOne` doesn't return a document. To safely access nested properties, use optional chaining (`?.`) and default values. Update your code like this: ```js const user = await db.findOne({ id: userId }); console.log(user?.profile?.name ?? 'Unknown'); ``` This prevents the error by returning `undefined` if `user` or `user.profile` is missing, and provides a fallback value.
2676f722-d517-4ec4-ab96-1c1ec80e06bd
The error occurs because user is undefined in some cases, likely when the query db.findOne doesn't return a document. To safely access nested properties, use optional chaining (?.) and default values. Update your code like this:
const user = await db.findOne({ id: userId });
console.log(user?.profile?.name ?? 'Unknown');This prevents the error by returning undefined if user or user.profile is missing, and provides a fallback value.