简体   繁体   中英

How to delete from two MongoDB collections using Node

I have a website with users and posts. There are two MongoDB collections, one for the users and one for the posts. I can delete through the website from each collection but I want that when I delete a user it will also delete all of the user's posts.

This is the code for deleting posts and users:

function deleteUser() {
  var confirmation = confirm("Are you sure?");
  if (confirmation) {
    $.ajax({
      type: 'DELETE',
      url: '/users/delete/' + $(this).data('id'),
      //url: '/posts/deletew/'+$(this).data('uploadedBy')
    }).done(function(response) {
      window.location.replace('/usersdata');
    });
    window.location.replace('/usersdata');
  } else {
    return false;
  }
}

$(document).ready(function() {
  $('.deletePost').on('click', function(e) {
    $target = $(e.target);
    const id = $target.attr('data-id');
    var confirmation = confirm('Are you sure?');
    if (confirmation) {
      $.ajax({
        type: 'DELETE',
        url: '/posts/delete/' + id,
        success: function(response) {
          console.log('here');
        },
        error: function(err) {
          console.log(err);
        }
      });
      window.location.replace('/posts/blog');
    }
  });
});

I handle the request with NodeJS on the server-side:

//delete users
app.delete('/users/delete/:id', function(req, res) {
  User.deleteOne({
    _id: ObjectId(req.params.id)
  }, function(err, result) {
    if (err) {
      console.log(err);
    }
    res.redirect('/');
  });
})

//delete post
app.delete('/posts/delete/:id', function(req, res) {
  Post.deleteOne({
    _id: ObjectId(req.params.id)
  }, function(err, result) {
    if (err) {
      console.log(err);
    }
    res.redirect('/blog');
  });
})

//delete post with deleted user that what i've been trying to do
app.delete('posts/deletew/:uploadedBy', function(req, res) {
  Post.deleteOne({
    uploadedBy: req.params.uploadedBy
  }, function(err, result) {
    if (err) {
      console.log(err);
    }
    res.redirect('/');
  })
})

If you know how to do it please answer. Thanks

I would suggest deletion operation of related 'posts' also inside " app.delete('/posts/delete/:id' " itself. SO that when you delete a user all the associated data from "posts" also will be deleted without the expense of another API endpoint. You can use MongoDB 'deleteMany' for this. for eg,

db.posts.deleteMany( { user_id : req.params.id } )

Adding to it. I would never suggest hard deleting a post from the user's collection just because the user is deleted. Instead, add another key in the post collection(say, 'deleted') and make this false by default and make it true on the user delete operation. Next time you do a find operation, give an extra filter as {deleted: false} so that you will not be having deleted user posts in the list. cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM