首页 > 解决方案 > 如何从用户集合中删除孤立的 objectid 引用?

问题描述

查找用户的控制器功能:

router.get("/:id", usersController.getUser)

getUser: async (req, res, next) => {
    try {
        const user = await User.findById(req.params.id)
        if (!user) {
            return res.status(404).json({ message: "User not found" })
        }
        return res.status(200).json({ user })
    } catch (error) {
        return next(error)
    }
}

我得到了这样的回应:

{
    "user": [
        {
            "posts": [
                "5e857785591a6c1047341c60",
                "5e85779f591a6c1047341c61"
            ],
            "_id": "5e84e15ef2ae067df522c164",
            "username": "rick",
            "email": "rickk3@gmail.com",
            "password": "$2b$10$FRHysk3eBMEOfS3FAT1nEe9voFH9yETR.3V1ZTJkg8Ekwtt6TlJ.W",
            "createdAt": "2020-04-01T18:45:50.029Z",
            "updatedAt": "2020-04-02T05:26:55.722Z",
            "__v": 9
        }
    ]
}

router.delete("/:id/delete", postsController.deletePost)

删除后控制器功能:

deletePost: async (req, res, next) => {
    try {
      const post = await Post.findByIdAndDelete(req.params.id)
      if (!post) {
        return res.status(200).json({ error: "No post found"})
      }
       res.status(200).json({ post })
    } catch(error) {
        console.log(error)
    }
  }

localhost:3000/api/v1/posts/5e857785591a6c1047341c60/delete

删除帖子后,我收到以下回复:

  {
    "post": {
        "_id": "5e857785591a6c1047341c60",
        "title": "helloooo",
        "description": "hello there",
        "user": "5e84e15ef2ae067df522c164",
        "createdAt": "2020-04-02T05:26:29.637Z",
        "updatedAt": "2020-04-02T05:26:29.637Z",
        "__v": 0
    }
}

现在,在我删除帖子后,我希望删除该ObjectID帖子在users集合中的引用。

现在,在数据库中,用户文档如下所示:

{
    "_id" : ObjectId("5e84e15ef2ae067df522c164"),
    "posts" :
        [
            ObjectId("5e857785591a6c1047341c60"),
            ObjectId("5e85779f591a6c1047341c61") 
        ],
        "username" : "rick",
        "email" : "rickk3@gmail.com",
        "password" : "$2b$10$FRHysk3eBMEOfS3FAT1nEe9voFH9yETR.3V1ZTJkg8Ekwtt6TlJ.W",
        "createdAt" : ISODate("2020-04-01T18:45:50.029Z"),
        "updatedAt" : ISODate("2020-04-02T05:26:55.722Z"),
        "__v" : 9
}

标签: node.jsmongodbexpressobjectid

解决方案


因此,在您成功删除Post调用集合以从数组user中提取该特定帖子 ID 之后。posts

试试下面的代码:

const mongoose = require("mongoose");

deletePost: async (req, res, next) => {
  try {
    const post = await Post.findByIdAndDelete(req.params.id);
    if (!post) {
      return res.status(200).json({ error: "No post found" });
    }
    await User.update(
      { _id: mongoose.Types.ObjectId(post.user) },
      { $pull: { "posts": mongoose.Types.ObjectId(post._id) } }
    ); /** You can check for n updated to make sure this operation is successful or else can re-try again */
    res.status(200).json({ post });
  } catch (error) {
    console.log(error);
  }
};

推荐阅读