MongoDB: How can populate reference, and delete element in array after based on the ID of the reference

Viewed 34

So I have a situation where I need to delete elements in an array of reference / ObjectIds, but the delete condition will be based on a field in the reference.

For example, I have schemas like the following:

const UserSchema = new mongoose.Schema({
   firstName: String,
   lastName: String,
   homeFeeds:[{type: Schema.Types.ObjectId, requried: true, ref: "Activity"}];
}); // User , is the referenece name

const ActivitySchema = new mongoose.Schema({
   requester: {type: Schema.Types.ObjectId, requried: true, ref: "User"},
   message: String,
   recipient: {type: Schema.Types.ObjectId, requried: true, ref: "User"},
}) // Activity, is the reference name

Now I need to delete some of the homeFeeds for a user, and the ones that should be deleted need to be by certain requester. That'll require the homeFeeds (array of 'Activity's) field to be populated first, and then update it with the $pull operator, with a condition that the Activity requester matches a certain user.

I do not want to read the data first and do the filtering in Nodejs/backend code, since the array can be very long.

Ideally I need something like:

await User.find({_id: ID})
          .populate("homeFeeds", "requester")
          .updateMany({
               $pull: {
                  homeFeeds.requester: ID
               }
          });

But it does not work, Id really appreciate if anyone can help me out with this?

Thanks

1 Answers

MongoDB doesn't support $lookup in update as of version v6.0.1.

MongoServerError: $lookup is not allowed to be used within an update.

Though, this doesn't have to do with Mongoose's populate as populate doesn't depend on $lookup and fires additional queries to get the results. Have a look at here. Therefore, even if, you could achieve what you intend, that is avoiding fetching a large array on nodejs/backend, using mongoose will do the same thing for you behind the scenes which defeats your purpose.

However you should raise an issue at Mongoose's official github page and expect a response.

Related