Skip to content

Instantly share code, notes, and snippets.

@DraCaster
Created June 7, 2021 19:49
Show Gist options
  • Save DraCaster/a12e9db14191272da6a6b65cedf712c4 to your computer and use it in GitHub Desktop.
Save DraCaster/a12e9db14191272da6a6b65cedf712c4 to your computer and use it in GitHub Desktop.
Moongoose aggregate $match does not match id
/*Your id variable will be constructed of "string", and not ObjectId value.
Mongoose "autocasts" string values for ObjectId into their correct type in regular queries,
but this does not happen in the aggregation pipeline, as in described in issue #1399:
https://github.com/Automattic/mongoose/issues/1399
Instead you must do the correct casting to type manually:*/
import mongoose from 'mongoose'
id = mongoose.Types.ObjectId(anyModel)
YourModel.aggregate([
{ "$match": { "_id": id }}
]).exec()
/*The reason is because aggregation pipelines "typically" alter the document structure,
and therefore mongoose makes no presumption that the "schema" applies to the document in any given pipeline stage.
It is arguable that the "first" pipeline stage when it is a $match stage should do this,
since indeed the document is not altered. But right now this is not how it happens.
Any values that may possibly be "strings" or at least not the correct BSON type need to be manually cast in order to match.*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment