javascript - 如何修复 Mongoose 模型的 deleteOne() 函数,当它不被 req.params.id 删除时?

标签 javascript node.js mongodb mongoose

首先要提到的是,我对 Node.Js 和 MongoDB 完全陌生。

我正在使用 Node.Js 和 MongoDB 编写后端 API,它将处理来自前端的 GET、POST、DELETE 请求,这些非常简单。

我在使用 DELETE 功能时卡住了。

这是我的 posts.service.ts 文件,其中包含此 deletePost() 函数,该函数将 postId 发送到后端 app.js文件。

`

deletePost(postId: string) {
    this.http.delete('http://localhost:3000/api/posts/' + postId)
    .subscribe(() => {
      console.log(postId);
      console.log('Deleted');
    });
  }

`

我已经添加了这个 console.log(postId) 来检查它是否真的包含实际的 postId 并发现它包含。我还通过 mongo shell 将其与 MongoDB 中的真实 ID 进行了匹配。

这是后端 app.js 文件中的 delete() 函数,它应该执行实际任务。

`

app.delete("/api/posts/:id", (req, res, next) => {
  Post.deleteOne({ _id: req.params.id }).then(result => {
    console.log(result);
    res.status(200).json({message: "Post deleted"});
  });
});

`

console.log(result) 行应该在终端中打印一些结果,但它没有,所以它不会删除数据库中的集合。

我在 Ubuntu 16.04 LTS 电脑上运行它。

一些线索意味着很大的帮助。非常感谢您的努力。

最佳答案

deleteOne 不会返回已删除的文档。它总是删除第一个匹配的文档,并用 bool 值返回删除的文档数。

来自 mongodb docs删除一个:

Returns:

  1. A document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled

  2. deletedCount containing the number of deleted documents

来自 Mongoose docs

Deletes the first document that matches conditions from the collection. Behaves like remove(), but deletes at most one document regardless of the single option.

关于javascript - 如何修复 Mongoose 模型的 deleteOne() 函数,当它不被 req.params.id 删除时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740078/

相关文章:

javascript - 从子窗口调用父窗口函数不起作用

javascript - 向所有监听器调度事件

javascript - 如何执行find中的函数或将数据保存在变量中?

node.js - req.session.id 不同于 req.session._id

mongodb - 无法理解 ubuntu 14.04 中的 Mongodb upstart ('/etc/init.d/mongod' ) 脚本

java - 如何使用 Java 将数据存储到 MongoDb 数据库中?

javascript - 为什么我的 Firebase 项目无需指定 apiKey 即可运行?

node.js - PDF.js - 将 pdf 拆分为多个页面并重新构建多个文件

spring - MongoDB GridFS 身份验证不起作用

javascript - jQueryeach与replaceWith结合问题