首页 > 解决方案 > 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 实际输出:未定义

没有错误消息。

标签: javascriptnode.jsmongodbvue.js

解决方案


您需要添加属性引用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>

推荐阅读