【问题标题】:Error while deleting a value of element in mongoDB array using filter function?使用过滤器函数删除mongoDB数组中的元素值时出错?
【发布时间】: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


    【解决方案1】:

    相信你会在这里找到一个好的答案: https://stackoverflow.com/a/4588909/9951599

    需要考虑的事情...

    您可以使用 MongoDB 的内置投影方法来简化您的代码。 https://docs.mongodb.com/manual/reference/operator/projection/positional/#mongodb-projection-proj.-

    通过为每个 cmets 分配一个“唯一 ID”,您可以使用更新命令快速查找/修改评论,而不是按数组中的顺序提取评论。这更有效,也更简单。此外,在繁忙时间一次多次读取/写入不会干扰此逻辑,确保您始终删除正确的评论。

    解决方案 #1:推荐的方式,使用原子运算符

    如果您给每个 cmets 一个 ID,您可以让 MongoDB 为您提取它。

    await db.collection('articles').updateOne({ name:articleName },
    {
        $pull:{ "comments.id":commentID }
    });
    // Or
    await db.collection('articles').updateOne({ name:articleName, "comments.id":commentID },
    {
        $unset:{ "comments.$":0 }
    });
    

    解决方案 #2 - 不推荐

    或者,您可以通过索引删除它:

    // I'm using "3" here staticly, put the index of your comment there instead.
    db.collection('articles').updateOne({ name:articleName }, {
        $unset : { "comments.3":0 }
    })
    

    我不知道您的过滤器为什么会出错,但我建议您完全绕过过滤器并尝试为您利用 MongoDB 的原子系统。

    【讨论】:

    • 虽然我正在尝试删除而不使用 findByIdandDelete();但我也在探索其他方法。得出你的答案,即在 Solution#2 中,你静态使用了 3 但我有一个变量 commentIndex ,那么我该如何在这里使用它,??? db.collection('articles').updateOne({ name:articleName }, { $unset : { comments.${commentIndex}:0 } }) 我像上面一样使用反引号和美元,就像我们在 javascript 中一样?
    • 还有你的方法 2 使空值产生问题
    猜你喜欢
    • 2016-09-19
    • 1970-01-01
    • 2022-08-11
    • 2020-06-14
    • 1970-01-01
    • 2015-06-12
    • 2016-10-07
    • 2017-12-22
    • 2019-03-03
    相关资源
    最近更新 更多