Express路由对象属性访问异常:部分属性值为Undefined
问题分析与解决方案
Hey there! Let's fix this tricky little issue you're running into.
核心问题:大小写敏感的属性名
从你的控制台输出和代码来看,问题根源其实是JavaScript的大小写敏感性:
- 打印出来的
notiSchema对象里,用户名属性是全小写的username:{ link: '5aa42e', image: '/Imgs/seholoko.jpg', title: 'Test', username: 'anthonyslips' } - 但你访问时用的是
userName(这里的N是大写的):console.log("\n NotiSchema Username:\n"+notiSchema.userName+"\n"); // 输出Undefined
在JavaScript里,username和userName是两个完全不同的属性名,所以用错误的大小写访问时,自然会返回undefined。
快速解决方案
把访问属性的代码改成和对象实际属性名一致的写法:
console.log("\n NotiSchema Username:\n"+notiSchema.username+"\n"); // 现在会正确输出'anthonyslips'
额外避坑建议
为了避免这类低级错误,给你两个小技巧:
- 定义MongoDB Schema时统一命名规范(比如全小写驼峰或下划线格式),不要中途随意变更大小写
- 可以用对象解构的方式访问属性,代码更清晰还能减少手动输入错误:
const { username, title, image, link } = notiSchema; console.log("\n NotiSchema Username:\n"+username+"\n");
内容的提问来源于stack exchange,提问作者Bruno Pigatto
相关产品推荐
相关产品推荐

