1

I have a function that will update a field for an object within an array in my MongoDB collection, when there is a match on the subscription_id for that array element. The code looks like this:

  if (mongoArrSubscription) {
    try {
      db.collection('clients').updateMany(
       { "subscription._id": { $in: mongoArrSubscription } },
       { $set :{ "subscription.0.subscriptionEnd": lastDayOfMonth,
                 "subscription.1.subscriptionEnd": lastDayOfMonth }},
        function (err, res) {
        if (err) throw err;
        console.log(res);
      });

      res.sendStatus(200);
    } catch (e) {
      console.log(e);
    }
  }

The problem is that some of the "subscription" arrays have one element, others have two. What I want do is add some conditional logic, prior to the $set, to ensure that the value is $set only if that array element exists. Because right now, if the second array element doesn't exist, this operation will create it, and insert that one value -- which is clearly not what I want.

I suppose even better would be to do some kind of forEach() loop to handle a situation where we might have more than two array elements in the future, though I'm not sure what this would look like.

Muirik
  • 6,049
  • 7
  • 58
  • 116

0 Answers0