gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:37:11 25 4
gpt4 key购买 nike

首先要提到的是,我对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com