0

I'm using size on a nested array:

totalRevisions: { $size: `$revisions.${entryId}.${languageId}` }

However before a revision is made this path won't exist. How can I prevent Mongo from throwing an exception "MongoError: The argument to $size must be an array, but was of type: missing" and return 0 for totalRevisions instead? Thanks.

Data structure:

project: {
  ...
  revisions: {
    <entryId1>: {
      <languageId1>: [revision, revision, ...],
      <languageId2>: [revision, revision, ...],
      ..more langs..
    },
    ..more entries..
  } 
}
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • Duplicate of : [MongoDB - The argument to $size must be an Array, but was of type: EOO](https://stackoverflow.com/q/24201120/2313887) – Neil Lunn May 10 '18 at 21:51
  • Thanks @NeilLunn and I even looked at ifNull oops. Voting to close. – Dominic May 10 '18 at 21:52
  • Voting for the nice person who answered the question with the solution might be polite – Neil Lunn May 10 '18 at 21:53
  • @NeilLunn Will do I was just trying to figure out why it's returning undefined regardless of what I put as the second arg in the ifNull array :/ – Dominic May 10 '18 at 22:02
  • Nested array as in `"revisions": [{ "something": [{ "notlanguage": [] }] }]`? Aside from nesting arrays like that being a very bad idea of course, but is this what you are talking about? As in if you still think it's an issue then you'd be better off actually showing a small sample of document to illustrate what exactly you mean. – Neil Lunn May 10 '18 at 22:10
  • It's working fine I just do `project.totalRevisions || 0` when returning the data. Bad idea in what sense? Sharding/perf? Added structure in question thanks – Dominic May 10 '18 at 22:23
  • 1
    You're structure is different from what I was talking about, and what I was talking about would need to be treated differently to get the `$size`. `$ifNull` works here, but you do actually need to use it to avoid the error and of course be returning an empty array `[]` and not a number. – Neil Lunn May 10 '18 at 22:37

0 Answers0