You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:30:05