1

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

Shaun
  • 61
  • 1
  • 1
  • 5
  • You will have to write an aggregation pipeline, to first filter the documents by id, then join the user and activity collections, filter out the feeds on the basis of requester id, and then update the document in the collection – Charchit Kapoor Aug 25 '22 at 05:58
  • I came up with similar problem today, I wanted to get the document first and then loop over the array and check. Did you find any solution? – inayatu Sep 23 '22 at 11:23

1 Answers1

0

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.

Rahul Sharma
  • 5,562
  • 4
  • 24
  • 48
  • thank you very much for the answer! I found a bulkUpdate method that MongoDB provide does what I want, that works fine for now. – Shaun Dec 29 '22 at 01:59