0

When I have one item left in an array and I remove it, the field becomes empty. Is there any option to check if there is one element left and then update the key with undefined instead of removing?

Here is what I have:

User.aggregate([
    {$match: {email: {$in: [email, friendEmail]}}},
    {
      $project: {
        friendSentRequests: {$size: {"$ifNull": ["$friendSentRequests", []]}},
        friendReceivedRequests: {$size: {"$ifNull": ["$friendReceivedRequests", []]}},
      }
    }],
  (err, result) => { ... }
);

With method written above I indeed get the array size, but batch throws errors that array is type missing if one doc doesn't have the key that second doc has. Unless I'm not supposed to make any updates in (err, result) => {..} function and there is another recommended way to update the object.

I don't want to set multi because I want to update via batch two different keys from different docs and I can't get the array length of each of these fields. Unless I'm misunderstanding how multi works.

0

1 Answer 1

2

if you want to confirm the number of elements in an array , e.g here is you want to check that the array has one element then:

{
    $match:{
      "myArray" :{ $size : 1 }
    }
}

And to check if array does not exist:

   {
    $match:{
      "myArray" :{ $exists: false}
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.