【问题标题】:MongoDB _id returns undefined on frontend (VueJS)MongoDB _id 在前端返回 undefined (VueJS)
【发布时间】:2019-06-07 16:44:24
【问题描述】:

我使用 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才能用于db查询。但是在前端(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 实际输出:未定义

没有错误信息。

【问题讨论】:

    标签: javascript node.js mongodb vue.js


    【解决方案1】:

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

    【讨论】:

    • 这正是我所拥有的?我在@dblclick 上有 post._id。您能否详细说明您的答案?谢谢。
    • 这不是你所拥有的。请注意,在我的回答中有一个 :post="post" 指令。
    • 你能发布响应返回的完整结构吗?
    【解决方案2】:

    您不必在前端将 _id 转换为 Mongo ObjectID。

    您的代码看起来很正常,将所有帖子对象发送到类似的功能并进行调试。

    @dblclick="deletePost(post)"

    可能您的后端将 _id 作为对象返回。

    【讨论】:

    • 我试图 console.log 这个 post 对象,但它只返回了 2 个属性(createdAt 和 text)的一堆 getter 和 setter。 :/ 我找不到关于 _id 的任何信息
    • 你应该检查后端代码。因为没有任何 _id 字段。
    猜你喜欢
    • 2021-02-25
    • 2018-05-09
    • 2018-09-07
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多