【发布时间】:2021-11-30 16:17:02
【问题描述】:
我试图在这里找到解决方案,但在使用 $pull 时无法成功,因为我拥有的数组值不包含 `mongo_id'。
所以情况是,我试图删除我通过查询参数传递的特定用户的特定评论。 M
我的 mongo 数据如下所示:
现在我在我的本地主机上发出这样的 API 删除请求:http://localhost:8000/api/articles/learn-react/delete-comment?q=1。
最后我的代码如下所示:
import express from "express";
import bodyParser from "body-parser";
import { MongoClient } from "MongoDB";
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect(
"mongodb://localhost:27017",
{ useNewUrlParser: true },
{ useUnifiedTopology: true }
);
const db = client.db("my-blog");
await operations(db);
client.close();
} catch (error) {
res.status(500).json({ message: "Error connecting to db", error });
}
};
app.delete("/api/articles/:name/delete-comment", (req, res) => {
const articleName = req.params.name;
const commentIndex = req.query.q;
withDB(async(db) => {
try{
const articleInfo = await db.collection('articles').findOne({name:articleName});
let articleAllComment = articleInfo.comments;
console.log("before =",articleAllComment)
const commentToBeDeleted = articleInfo.comments[commentIndex];
//console.log(commentToBeDeleted)
// articleAllComment.update({
// $pull: { 'comments':{username: commentToBeDeleted.username }}
// });
articleAllComment = articleAllComment.filter( (item) => item != commentToBeDeleted );
await articleAllComment.save();
console.log("after - ",articleAllComment);
//yaha per index chahiye per kaise milega pta nhi?
//articleInfo.comments = gives artcle comment
res.status(200).send(articleAllComment);
}
catch(err)
{
res.status(500).send("Error occurred")
}
},res);
});
我使用了filter 函数,但它在终端中没有显示任何错误,而且在邮递员处也获得了 500 状态。
无法找出错误?
【问题讨论】:
标签: javascript node.js mongodb api express