I want to return all documents in a collection. But I only want a subdocument to appear in votes array if the userId matches. If it doesn't match I still want the parent document to be returned but without anything appearing in the votes array.
Actual document:
[{ "_id": "...",
"user": {...},
"title": "test",
"votes": [
{"user": "56c265fda0a4335c01205551", "vote": 1},
{"user": "56c265fda0a4335c01205552", "vote": 1},
{"user": "56c265fda0a4335c01205553", "vote": 1},
{"user": "56c265fda0a4335c01205554", "vote": 1}
]}]
What I want if the filter is ...5551: (It IS in the array)
[{ "_id": "...",
"user": {...},
"title": "test",
"votes": [
{"user": "56c265fda0a4335c01205551", "vote": 1}
]}]
What I want if the filter is ...0000: (It isn't in the array)
[{ "_id": "...",
"user": {...},
"title": "test",
"votes": [] //Empty array, but document is still returned.
}]
I found a lot of resources to only include documents if the search value appears in the array, and I can get that value to be the only one that appears, but all of these don't return documents if that value isn't found in the array at all.
How do I get all parent documents to be returned and then filter the votes array so only a single matching element is returned if it is there?
Note: My question is very similar to Retrieve only the queried element in an object array in MongoDB collection but is specific to implementing in Mongoose, not MongoDB.