Tuesday, 4 April 2017

How to delete Element In MongoDB property's array with MongooseJS?

I cannot remove an element inside of an array that is a property of a MongoDB Model. Please remember this is a NodeJS module mongooseJS and not the real MongoDB so functionalities are not the same..

GOAL: Delete an object from the statusLiked array. | I have also confirmed that the value of status.id is correct.

Model:

 Const userSchema = new mongoose.Schema({
  myStatus: Array,
  statusLiked: Array,
 )};

Delete: 1. Deletes the status(works). 2. Delete the status from User.statusLiked(no work).

exports.deleteStatus = (req, res, next) => {
  var CurrentPost = req.body.statusid; // sends in the status.id
  Status.remove({ _id: CurrentPost }, (err) => {
    if (err) { return next(err); }
    // vvvv this vvv
    User.update( {id: req.user.id}, { $pullAll: {_id: CurrentPost }, function(err) { console.log('error: '+err) } });

    req.flash('success', { msg: 'Status deleted.' });
    res.redirect('/');
  });

};

What happens: The specific status(object) is deleted from the database. But the status still remains in the User.statusLiked array.

What I want to happen: Status to be deleted from the User.statusLiked array and the status to be deleted from the database. Then, reload the page and display a notification.



via Tyrese Williams

No comments:

Post a Comment