Why does a Mongoose 9 Order.aggregate() report match nothing for a user id string from the URL while Order.find() with the same filter works?
answer
- who converts the types
- queries cast at exec
- pipelines pass through untouched
- ObjectId and Date by hand
- plain objects come back
basics
~20 sMongoose casts Query filters against the schema but sends Model.aggregate pipelines uncast, so a hex string never equals a stored ObjectId, and a date string never equals a stored Date. Convert values yourself; results come back as plain objects.
solid answer
~40 sWhen a query executes, Mongoose **casts** its filter using the schema: `{ user: '64b7...' }` becomes an `ObjectId`, `{ total: { $gt: '10' } }` a number, and an uncastable value throws a `CastError`. `Model.aggregate()` does not cast its pipeline, because stages such as `$project` and `$group` can reshape documents so the schema no longer describes them. A `$match` on `user: req.params.userId` therefore compares a string with an `ObjectId` and matches nothing; the same happens to `createdAt: { $gte: '2026-01-01' }`. Build typed values yourself: check with `mongoose.isObjectIdOrHexString()`, then `new mongoose.Types.ObjectId(id)` and `new Date(...)`, or `Order.castObject()` for equality values. Aggregate also returns plain objects, and runs only `aggregate` middleware, so a soft-delete `pre('find')` hook does not apply.
code
javascript · 20 lines// Query middleware does not apply to aggregate, so the soft-delete filter
// needs its own hook, registered before the model is compiled
orderSchema.pre('find', function () {
this.where({ isDeleted: { $ne: true } });
});
orderSchema.pre('aggregate', function () {
this.pipeline().unshift({ $match: { isDeleted: { $ne: true } } });
});
const Order = mongoose.model('Order', orderSchema);
const id = '64b7f0c2a1b2c3d4e5f60718';
// Cast at exec time: the string becomes an ObjectId, so this matches
await Order.find({ user: id });
// Not cast: compares a string with stored ObjectIds and matches nothing
await Order.aggregate([{ $match: { user: id } }]);
// Typed by hand: matches
await Order.aggregate([{ $match: { user: new mongoose.Types.ObjectId(id) } }]);go deeper
Remember that Model.aggregate() does not convert strings to ObjectIds or Dates the way find() does, and that its results are plain objects.
Explain query casting at exec time, the implicit $in, CastError for bad values, and the three strictQuery settings with what each does to an unknown filter path.
Diagnose an empty report from the types in $match, fix it with explicit ObjectId and Date values behind input checks, and carry soft-delete or tenant filters into pre('aggregate') hooks.
Decide how far aggregation pipelines may spread in a codebase and what guards they need, such as shared helpers that type request values and a strictQuery setting that surfaces typos.
## How a Query is cast **Casting** is Mongoose converting a value to the type a schema path declares. For queries it happens at execution time, when you `await` the query or call `exec()`: 1. Mongoose walks the filter and looks up each path in the schema. 2. Values on known paths are converted: a 24-character hex string on an `ObjectId` path becomes an `ObjectId`, `'50'` under `$gt` on a `Number` path becomes `50`, an ISO string on a `Date` path becomes a `Date`. 3. An array given for a non-array path gets an implicit `$in`. 4. A value that cannot be converted makes the query reject with a `CastError`, such as `Cast to ObjectId failed for value "nope"`. That is why `Order.find({ user: req.params.userId })` works with a string straight from the URL. ## Paths the schema does not know: strictQuery Casting needs a schema path. For filter keys the schema does not declare, the `strictQuery` option decides, and its default is `false`: | `strictQuery` | Unknown path in the filter | Typical effect | |---|---|---| | `false` (default) | sent as-is, value not cast | usually matches nothing | | `true` | silently removed | may match far more documents than intended | | `'throw'` | `StrictModeError` | the bug surfaces immediately | A misspelled `{ custmer: id }` therefore usually returns an empty list by default, and every order under `strictQuery: true`. Set it per schema or globally with `mongoose.set('strictQuery', ...)`. ## Why Model.aggregate is different `Order.aggregate([...])` builds a Mongoose `Aggregate` and sends the pipeline to the server as written. The Mongoose API docs give the reason: `$project` and `$group` can redefine the shape of documents at any stage, so the model's schema may no longer describe them. The consequences: - **No casting.** `{ $match: { user: '64b7...' } }` compares a string with stored `ObjectId` values and matches nothing, silently. The same applies to dates, numbers sent as strings and booleans sent as `'true'`. - **Plain objects out.** Results are never hydrated: no getters, no virtuals, no `save()`, and `instanceof mongoose.Document` is `false`. - **Different middleware.** `Model.aggregate()` runs `pre('aggregate')` and `post('aggregate')` hooks only. A soft-delete `pre('find')` hook that adds `isDeleted: false` does not touch the report; add a `pre('aggregate')` hook that unshifts a `$match` onto `this.pipeline()`. - **No `select: false`, no defaults.** Fields hidden or defaulted by the schema behave as they are stored. ## The report, fixed The monthly revenue report for one customer must convert its inputs before they enter the pipeline: ```javascript if (!mongoose.isObjectIdOrHexString(req.params.userId)) { return res.status(400).json({ error: 'invalid id' }); } const rows = await Order.aggregate([ { $match: { user: new mongoose.Types.ObjectId(req.params.userId), status: 'paid', createdAt: { $gte: new Date(req.query.from) } } }, { $group: { _id: { $dateToString: { format: '%Y-%m', date: '$createdAt' } }, revenue: { $sum: '$total' } } }, { $sort: { _id: 1 } } ]); ``` The guard matters because `new mongoose.Types.ObjectId('nope')` throws a `BSONError` rather than the `CastError` a query would give, and a `Date` built from a malformed string is an Invalid Date that raises no error at all, so validate `from` as well (for example, reject it when `Number.isNaN(date.getTime())`). For equality values on schema paths, `Order.castObject({ user: id })` returns a plain object with the schema's types applied, and throws a `ValidationError` when a value cannot be cast. What `$group` and `$dateToString` compute is the MongoDB aggregation material's subject; Mongoose's part is only that it passes them through. ## A checklist for every pipeline - Convert every id, date and number that came from a request before it enters `$match`. - Put the soft-delete and tenant filters that query middleware applies into `pre('aggregate')` as well. - Treat the output as plain objects with the shape your `$project` or `$group` produced. - Prefer a query when it can answer the question; reach for `Model.aggregate()` when you need grouping, joins or reshaping. - Add a test that runs the pipeline with values typed exactly as the route receives them, strings included, so a missing conversion fails in the suite rather than as an empty report. The Mongoose API docs also mention a third-party plugin that adds minimal casting to aggregation pipelines; whether you adopt one or not, knowing that the default is no casting at all is what lets you diagnose the empty report in minutes.
- With Mongoose 9 defaults, what does Order.find({ custmer: id }) return when custmer is a typo?Usually an empty list. `strictQuery` defaults to `false`, so Mongoose sends the unknown path as-is and uncast, and no stored order has that field. With `strictQuery: true` the path is stripped and the query returns every order, which is the more dangerous failure; `strictQuery: 'throw'` raises a `StrictModeError` and surfaces the typo.
- Why does a Mongoose soft-delete hook on pre('find') not hide deleted orders from Order.aggregate()?`find` hooks are query middleware and only fire for query operations. `Model.aggregate()` has its own `aggregate` middleware, where `this` is the `Aggregate` object. Register `pre('aggregate')` and unshift a `$match` onto `this.pipeline()` so every pipeline starts with the same filter.
- Mongoose casts $match values in Model.aggregate() just like query filters.
- Model.aggregate() returns Mongoose documents when the output keeps the schema's shape.
- A pre('find') hook also filters Model.aggregate() pipelines.
- strictQuery defaults to true, so unknown filter paths are stripped.
- Chaining lean() onto an aggregate makes its results plain objects.