【问题标题】:Why pull is not removing elements为什么拉不删除元素
【发布时间】:2021-01-09 00:26:22
【问题描述】:

我一直在尝试从数组中删除元素,似乎它不起作用,这是模型 1。问题模型

   {

    reviews: [{ type: ObjectID, ref: 'Review' }]

   }

2。审查模型

    {
      description: {
      type: String
    },
      userId: {
      type: ObjectId,
      ref: 'User'
    }
   }

这是我为 Quuestion.js 提供的服务

export const deleteReview = async ({ reviewId, id }, user) => {
  try {
    const result = await Question.updateOne(
      { _id: id },
      {
        $pull: { reviews: { _id: reviewId, userId: user._id } }
      }
    ).exec();
    if (result.nModified === 0) {
      throw new APIError({ message: msg('Unauthorized'), status: 401 });
    }
    return result;
  } catch (error) {
    throw error;
  }
};

路线文件

  router.delete('/questions/:id/reviews/:reviewId', auth, async (req, res) => {
    try {
      const {
        params,
        user
      } = req;
      const data = await deleteReview( params,
        user);
      return res.status(200).json({ data });
    } catch (err) {
      error(res, err);
    }
  });

我试图删除元素,但它根本没有删除,我不知道我在哪里做错了。

【问题讨论】:

  • 尝试遵循此问题的最佳答案,这似乎与您正在做的事情很接近:stackoverflow.com/questions/48988019/…
  • 我也遵循同样的方法,似乎 $pull 运算符仅通过指定查询来删除元素,@kibe

标签: node.js mongodb mongoose


【解决方案1】:

这是我得到的解决方案,$pull 不起作用,所以应用了 $pullAll

export const deleteReview = async ({ reviewId, id }, user) => {
  try {
    const result = await Question.updateOne(
      { _id: id },
      {
        $pullAll: { reviews: [{ _id: reviewId, userId: user._id }] }
      }
    ).exec();
    if (result.nModified === 0) {
      throw new APIError({ message: msg('Unauthorized'), status: 401 });
    }
    return result;
  } catch (error) {
    throw error;
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2016-04-30
    • 2013-06-21
    • 2021-11-28
    相关资源
    最近更新 更多