javascript - MongoDB _id 在前端返回 undefined (VueJS)
问题描述
我使用 NodeJS & Express + MongoDB 创建了一个简单的全栈 web 应用程序来构建后端 API 和前端的 Vue.JS。
所有的 Write Read 和 Delete API 都运行良好(我使用 Postman 对其进行了测试)。一切都在前端工作得很好,除了当我试图在一个对象数组上迭代(v-for)以获得_id时,它不起作用。
名为posts 的数组具有'text' 和'createdAt' 的属性。v-for 完美运行并按预期输出 2 个属性。但是,我尝试输出 _id(来自 MongoDB 的默认 id),但它返回“未定义”。
这会导致问题,因为如果我无法获得 _id,我就无法使用现有的后端删除 API 删除特定帖子。
据我了解,在后端,_id需要先转换为ObjectId才能用于数据库查询。但是在前端(vue)上,我不确定如何将 _id 转换为 ObjectId。我在这里进入正确的方向吗?
<div class="post" v-for="(post,i) in posts " :key="post._id" :index="i" :item="post" @dblclick="deletePost(post._id)">
{{post.createdAt.getDate()}}/{{post.createdAt.getMonth() + 1}}/{{post.createdAt.getFullYear()}}
<p class="text">{{post.text}}</p>
</div>
...
methods: {
async deletePost(id){
console.log(id) //this returns undefined
await PostService.deletePost(id);
this.posts = await PostService.getPosts();
}
},
...
//del post in PostService.js
static deletePost(id){
return axios.delete(url+id)
}
//backend delete api
router.delete('/:id',async (req,res)=>{
const posts = await loadPostCollection()
console.log(ObjectID(req.params.id))
await posts.deleteOne({_id: ObjectID(req.params.id)});
res.status(200).send()
})
预期输出:每个“帖子”的_id,例如:5cfa8c29f74c65ae485a6d93 实际输出:未定义
没有错误消息。
解决方案
您需要添加属性引用post
,如下所示:
<div class="post" v-for="(post,i) in posts " :key="post._id" :post="post" @dblclick="deletePost(post._id)">
{{post.createdAt.getDate()}}/{{post.createdAt.getMonth() + 1}}/{{post.createdAt.getFullYear()}}
<p class="text">{{post.text}}</p>
</div>
推荐阅读
- html - Flexbox - 在自己的行上有项目,但只有 50% 宽
- r - 在 sommer 包中处理不同的性别
- git - Git 合并策略——我们的用例
- reactjs - 在 React 中单击子元素时更改父元素的样式
- java - 在 Java 数组中查找第一个匹配项(仅第一个匹配项)
- python-3.x - 为什么我在这个 else if 语句上出现语法错误?
- node.js - 表达正则表达式除 api/login/ 之外的所有路由
- api - Feedly API - 如何获取提要内容
- java - 将 Java 文件转换为 Kotlin 现在无法编译 - “内部编译器错误”
- automation - 与参数并行运行程序的多个实例的脚本