Search code examples
node.jsmongodbexpressobjectid

How to delete orphaned objectid reference from the users collection?


Controller function to find a user:

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)
    }
}

And I get this response:

{
    "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)

Deleting a post controller function:

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

After deleting a post, I get this response:

  {
    "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
    }
}

Now after I delete a post, I want the ObjectID reference that the post has in the users collection to delete.

Right now, in the database, the user document looks like this:

{
    "_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
}

Solution

  • So after your successful deletion of Post make a call to user collection to pull out that particular post id from posts array.

    Try below code :

    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);
      }
    };