Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow null values inside $expr objects #12429

merged 1 commit into from Sep 14, 2022


Copy link

@MartinDrost MartinDrost commented Sep 14, 2022


Version 6.2.0 introduced a feature which casts literals inside $expr queries to their respective types based on the models schema. This pull request fixes an issue with this feature where JS would throw a null-reference error when using null as a value inside $ifNull arrays in the expression.

The implemented fix is non-intrusive an solely checks if the value which is to be cast is null and preserves the value if it is.


A common scenario is reproducing an $exists operator in an $expr using $ifNull. Let's say we want to fetch all books which don't have an authorId or where the authorId is null.

await bookModel.find({ $expr: { $eq: [ { $ifNull: [ "$authorId", null ] }, null ] } })

Executing this code will output the following error

TypeError: Cannot read properties of null (reading '$cond')
    at _castExpression (E:\project\node_modules\mongoose\lib\helpers\query\cast$expr.js:85:11)
    at E:\project\node_modules\mongoose\lib\helpers\query\cast$expr.js:94:26
    at (<anonymous>)
    at _castExpression (E:\project\node_modules\mongoose\lib\helpers\query\cast$expr.js:94:17)
    at castComparison (E:\project\node_modules\mongoose\lib\helpers\query\cast$expr.js:206:12)
    at _castExpression (E:\project\node_modules\mongoose\lib\helpers\query\cast$expr.js:105:18)
    at cast$expr (E:\project\node_modules\mongoose\lib\helpers\query\cast$expr.js:76:10)
    at cast (E:\project\node_modules\mongoose\lib\cast.js:87:13)
    at model.Query.Query.cast (E:\project\node_modules\mongoose\lib\query.js:5312:12)
    at model.Query.Query._castConditions (E:\project\node_modules\mongoose\lib\query.js:2198:10)

@vkarpov15 vkarpov15 added this to the 6.5.6 milestone Sep 14, 2022
Copy link

@vkarpov15 vkarpov15 left a comment

Thanks 👍

@vkarpov15 vkarpov15 merged commit c35dfdd into Automattic:master Sep 14, 2022
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

Successfully merging this pull request may close these issues.

None yet

2 participants