I am encountering an issue where an aggregation query is returning an empty array, even though I expect it to return matching documents from my collection. Here’s the relevant portion of my code:
When running the code, I receive an empty array, even though there are documents with this collectionId in the database.
I have verified that the value of collectionId is correct and matches the documents in the collection. However, the aggregation still returns an empty array. When I use a regular find query, it works fine:
Your tests then eliminate issues with code logic. Good.
This last observation points to the direction of type mismatched between the stored value and the runtime type of the variable collectionId. For example, if the collectionId field is stored as a number, then the runtime type of the variable collectionId must also be a number. A frequent error, is that we get the variable value from a HTML form and the values are strings unless converted.
So what I suspect is that you do not obtain the value of collectionId using the same mean in the find vs the aggregate case. So it works with find because the runtime type of collectionId is correct while it is not correct for aggregate. For example, it could be the case that for find you do:
I moved your thread to Working with Data since your issue is not Atlas specific. I also add the tag mongoose-odm because NeNaD’s reply makes a lot of sense and it is a potential source of type mismatch.
Please try the suggestion
and if it works please mark NeNaD’s post as the solution.