You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js操作MongoDB如何删除文档中完整的eventsFollowing数组

解决方案

问题排查

  • 异步函数缺少await关键字:User.update()是异步操作,不加await的话函数会直接结束,数据库更新请求不会正常执行。
  • 方法过时:Mongoose 新版本中update()方法已被弃用,建议替换为updateOne()保证兼容性。
  • $unset语法本身是正确的,该操作符就是用于从文档中移除指定字段,完全满足删除整个eventsFollowing数组的需求。

正确实现代码

场景1:删除整个eventsFollowing数组字段

exports.deletfollow = async (req, res, next) => {
  try {
    const Author = req.body.userId;
    const updateResult = await User.updateOne(
      { _id: Author }, 
      { $unset: { eventsFollowing: "" } }
    );
    // 可根据updateResult的matchedCount、modifiedCount判断操作结果
    res.status(200).json({ message: "删除成功", data: updateResult });
  } catch (err) {
    next(err);
  }
};

场景2:仅删除eventsFollowing数组中指定followingId的元素(你代码中提取了followingId参数,大概率是该真实需求)

如果你的需求是移除数组内指定ID的项,而非删除整个数组字段,使用$pull操作符实现:

exports.deletfollow = async (req, res, next) => {
  try {
    const Author = req.body.userId;
    const eventFollowingId = req.body.followingId;
    const updateResult = await User.updateOne(
      { _id: Author }, 
      // 如果eventsFollowing存储的是对象,要匹配对象属性就写成 { $pull: { eventsFollowing: { _id: eventFollowingId } } }
      { $pull: { eventsFollowing: eventFollowingId } }
    );
    res.status(200).json({ message: "删除指定关注项成功", data: updateResult });
  } catch (err) {
    next(err);
  }
};

内容的提问来源于stack exchange,提问作者POLOS Tutorials

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:06:02