node.js - 通过 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。请调查一下。谢谢你。
解决方案
推荐阅读
- visual-studio - MSB3073 以代码 3 退出 - Visual Studio 2017 中的构建后事件
- c# - 将 C# 属性传递给 onChange 事件
- python - 带有动态修改表格的选择器的 Web 抓取表格
- azure-blob-storage - Mosaic 是否支持提取压缩数据?
- java - 检查两个三位数是否有任何在Java中相同的数字
- php - 显示特定用户角色的含税或不含税的 WooCommerce 产品价格
- python - 如何在python中添加WAKE-UP功能?
- jquery - 如何在 mvc5 razor 视图中的 jquery 代码中放置 @ 符号
- git - 还原文件时如何防止执行 git post-checkout 挂钩?
- azure - 从 MVC 5(Azure AD) 访问 WebAPI 时,此请求的授权被拒绝