0

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
}
ubuntu7788
  • 115
  • 2
  • 10
  • So as your deletion of post is successful after that you can internally make a DB call to `user` collection to pull that `_id` element from `posts` array, Try this :: (https://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb) Remember to convert `_id` returned in delete post response is string so convert it to `ObjectId()` & pull from `posts` array of `users` collection by checking in which user docs this exists using `$in`. Try it & Let me know if any issues.. – whoami - fakeFaceTrueSoul Apr 02 '20 at 06:00
  • User.update( { _id: post.user }, { $pull: { 'user.posts': { 'what should i do here' } } } ); – ubuntu7788 Apr 02 '20 at 06:04

2 Answers2

1

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);
  }
};
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
0

using mongoose easly https://mongoosejs.com/docs/api/model.html#model_Model.findByIdAndDelete

  var users = require('../Models/User.model');
    users.findOneAndRemove({ _id: req.params.id }, function (err) {
        if (err) {
            console.log("when delete account Encountered an error !");
        }

        res.redirect('/Account/index');
    });

../Models/User.model.js example

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var usersSchema = new Schema({
    username: { type: String, required: true/* , unique: true */ },
    password: { type: String, required: true },
    date: { type: Date, default: Date.now }

});

var users = mongoose.model('users', usersSchema);
module.exports = users;
hyperneu
  • 11
  • 2