The film collection has a review array of objects which holds the userid who made the review:
The user collection has a filmsReviewed array of object storing all the films that user reviewed:
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
You first need to query the
user
collection and get the_id
andfilmReviewed
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 (usingfilmReviewed
array). You can use $in operator for this.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.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);