Vue.js项目开发报错Cannot read property 'find' of undefined如何解决
问题解答
语法正确性判断
const singleProductComment = await comments.find((comments) => comments.postID === doc._id); 这行代码语法层面不会抛出语法错误,但存在用法错误:Array.prototype.find() 是JS原生同步数组方法,不需要搭配await使用,此处的await属于多余写法。
报错根因
运行时提示数据为undefined来自两个核心逻辑错误:
- axios 请求返回的响应对象中,接口返回的实际数据默认挂载在
data属性下,你直接从axios返回的顶层响应对象解构comments,无法取到对应值,导致comments本身为undefined,调用undefined.find就会抛出对应报错。 - MongoDB 查询返回的
doc._id是ObjectId类型,和评论数据里的postID(字符串/数字类型)用===全等比较时,会因为类型不一致无法匹配到结果。
修正后代码
app.get ('/products&comments/:title', async (req , res) => { const title = req.params.title; const db = await connect(); const doc = await db.collection("posts").findOne({title: title}); // 从响应的data属性中取接口返回的评论数据 const { data: { comments } } = await axios.get("http://localhost:4201/comments"); // 去掉多余await,将ObjectId转为字符串后再匹配 const singleProductComment = comments.find((comment) => comment.postID === doc._id.toString()); console.log(singleProductComment) res.json(singleProductComment) });
内容的提问来源于stack exchange,提问作者Jan Tuđan
相关产品推荐
相关产品推荐

