[MongoDB] How to Fix "$err" : "Can't canonicalize query: BadValue cannot compare to undefined", "code" : 17287
I’ll introduce how to fix the error “$err” : “Can’t canonicalize query: BadValue cannot compare to undefined”, “code” : 17287 that occurs in MongoDB.
> db.users.findOne({ _id: undefined });
2018-09-20T17:51:00.428+0900 E QUERY [thread1] Error: error: {
"$err" : "Can't canonicalize query: BadValue cannot compare to undefined",
"code" : 17287
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBQuery.prototype.next@src/mongo/shell/query.js:297:1
DBCollection.prototype.findOne@src/mongo/shell/collection.js:291:15
@(shell):1:1
When executing MongoDB queries without existence checks as shown below, you may occasionally encounter the “Can’t canonicalize query: BadValue cannot compare to undefined” error.
var comment = db.comments.findOne();
var user = db.users.findOne({ _id: comment.user });
// If comment.user is undefined, the following error occurs:
/**
E QUERY [thread1] Error: error: {
"$err" : "Can't canonicalize query: BadValue cannot compare to undefined",
"code" : 17287
}
**/
var comment = db.comments.findOne();
// If there's no guarantee that comment.user has a value, it's tedious but you have no choice but to check for existence
if (comment && comment.user) {
var user = db.users.findOne({ _id: comment.user });
}
That’s all about encountering code that applies undefined variables to MongoDB query conditions from the Gemba.