首页 > 解决方案 > 通过 Array.find() 在 post 路由中从 mongoose 访问数组对象的问题

问题描述

这是我的架构

const blogerSchema = new mongoose.Schema({
  username: String,
  password: String,
  blogs: Array,
});

博客看起来像

[
    {
      title: 'abc',
      content: 'abcabcabcabcabc'
    },
    {
      title: 'Hello world!',
      content: 'hello world how are you. to be honest i am not.\r\n'        
    }
  ]

现在这是我遇到问题的 app.post 路线之一。

app.post("/user/:username/:title/delete", function(req, res){
  const username = req.params.username;
  Bloger.findOne({username: username}, function(err, foundBloger) {
    const blogs = foundBloger.blogs.toObject();
    // console.log(blogs.length);
    blogs.find(function(post, index){
      console.log(post.title);
      if(post.title === req.params.title){
        _.pull(blogs, post);
        // Bloger.updateOne({username: username}, {blogs: blogs});
      }
    });
  });
  res.redirect("/user/"+username);
});

当我点击提交按钮时,该按钮会使用 url 访问此帖子路由http://localhost:3000/user/Aman/abc。我收到这个错误

[nodemon] starting `node app.js`
Server running on port 3000
abc
events.js:292
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'title' of undefined
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\app.js:148:24
    at Array.find (<anonymous>)
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\app.js:147:11
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\mongoose\lib\model.js:4844:16
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\mongoose\lib\model.js:4844:16
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\mongoose\lib\model.js:4867:21
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\mongoose\lib\query.js:4476:11
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\kareem\index.js:136:16
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
Emitted 'error' event on Function instance at:
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\mongoose\lib\model.js:4846:13
    at C:\The Web Devlopment Bootcamp 2020\firstBolgProject\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
[nodemon] app crashed - waiting for file changes before starting...

现在这里只是event.js:292它上面的一行,console.log(post.title)但在下一行它给了我 TypeError。请调查一下。谢谢你。

标签: node.jsarraysexpressmongoosetypeerror

解决方案


推荐阅读