Node.js + MongoDB query not working properly with "$or" object Node.js + MongoDB query not working properly with "$or" object express express

Node.js + MongoDB query not working properly with "$or" object


Have you tried this in console: x = db.users.findOne({ $or: [ {nickname:"mmellado"}, {_id:ObjectId("mmellado")} ]}). You'll see an error even if nickname matches because it first tries to convert "mmellado" into an ObjectId and fails. This is might be the reason your page fails when using nickname.

I don't know the node.js mongodb-driver internals, but it probably tries to convert the argument internally to ObjectId before querying for "_id" field (and fail if not valid). I didn't check this, so try it out. Also try checking the err object on the callback. If that is the problem one way to solve this is to check is argument is valid ObjectId before querying , for example create ObjectId out of it yourself and catch exception if it fails. Something like this (not tested):

try {  var objectId = createObjectId(req.params.id); // Create this function yourself  User.findOne( { "_id": objectId }, callbackFunction );} catch (err) {    // Fall back to using nickname    User.findOne( { "nickname": req.params.id }, callbackFunction );}


Default _id values are 12 byte binary hashes so you first need to convert the string into binary before you send the query using ObjectID.createFromHexString like this:

var id = ObjectID.createFromHexString(idHex);

Then use id in your query.

Your code should look something like this:

User.findOne( { $or : [{ "nickname": req.params.id },{ "_id": ObjectID.createFromHexString(req.params.id) }] }, function(err, user) { ........

Greetings Finch!!!