skip to Main Content

The film collection has a review array of objects which holds the userid who made the review:enter image description here

The user collection has a filmsReviewed array of object storing all the films that user reviewed:
enter image description here

I want to delete a user which I know how to do but before I need to delete all the film reviews made by this user on films. I know how to perform the deletion of a review but don’t know how to search for the films to be deleted within the films collection based on the filmReviewed array of objects in the User collection.

// search for all film reviews made by this user
//????????

// delete all film reviews made by this user for a specific film
await Film.findOneAndUpdate(
      {_id:request.params.filmid}, 
      {$pull:{reviews:{userid:mongoose.Types.ObjectId(request.body.userid)}}});

// delete the user
const opResult=await User.findByIdAndRemove(request.params.id);

Any ideas?

2

Answers


  1. You first need to query the user collection and get the _id and filmReviewed values of the particular user.

    Once you have this info, you now need to query film collection and find all the films where the above user left the reviews on (using filmReviewed array). You can use $in operator for this.

    let filmsToUpdate = await Film.find( { _id : { $in : filmReviewed } } );
    

    This will return all the movies where above user left the reviews on, then you can use $pull like you did in your question to update all the movies.

    Finally once everything is deleted, delete the above user (you already have user’s _id, we saved it above).

    EDIT

    In order to get filmReviewed array, you can just use .findOne() on user collection.

    // This will return whole user object
    let user = await user.findOne({ _id: request.params.id });
    
    // Select filmsReviewed property from the above object
    let filmReviewed = user.filmsReviewed;
    
    Login or Signup to reply.
  2. Just do this,

    // Extract the list of films reviewed by this user.

    const user = await User.findById(req.body.userid).select(‘filmsReviewed’);

    // This will return an object with String: _id and an Array: filmsReviewed

    // Extract the films array

    const filmsReviewed = user.filmsReviewed ;

    // Now use updateMany to update the films.

    await Film.updateMany({_id: req.params.filmid}, {$pull:{reviews:{userid:mongoose.Types.ObjectId(request.body.userid)}}});

    // And finally delete the user

    await User.findByIdAndRemove(request.params.userid);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search