1

I solved the same problem the author of this question had with the solution the other guy posted as an answer: Unwind empty array in mongodb

These days i updated my mongodb/mongoose and now i am getting an error:

MongoError: The top-level _id field is the only field currently supported for exclusion

It seems like mongo tries to "exclude" this field from the project now because of the 0 value.

I need to add an array with an object with {value:0} because otherwise this object will be ignored after the unwind.

  { $match: parameter},
  { $unwind : "$items" },
  { $project: {
    itemName: '$items.name'},
    itemValue : "$items.value",
    discount : { $cond : [ { $eq : ["$items.discounts", [] ]}, [ { value : 0} ], '$items.discounts'] } 
  }},  
  { $unwind: "$discount"},

Is there any other/newer solution to this problem? Thanks for your help.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Stefan F.
  • 138
  • 1
  • 8
  • Can you [edit] your question to include some sample documents for testing and the expected output from those documents? – chridam Sep 09 '16 at 06:58

1 Answers1

0

I don't really understand your problem, first i would change the aggregation to :

{ $match: parameter},
  { $unwind : "$items" },
  { $project: {
    itemName: '$items.name'},
    itemValue : "$items.value",
    discount : { $cond : [ { $eq : ["$items.discounts", []}, [ null ], '$items.discounts'] } 
  }},  
  { $unwind: "$discount"}

The above works for me. I would advise you to try it with your favorite editor or in mongoshell and check if it's working.

HoefMeistert
  • 1,190
  • 8
  • 17