filter mongodb object result by ObjectId with Underscore filter mongodb object result by ObjectId with Underscore mongoose mongoose

filter mongodb object result by ObjectId with Underscore


Sadly mongodb ObjectId instances do not work properly with JavaScript's equality operators == or ===. You either need to use the provided method: objectId1.equals(objectId2) or ensure they are both converted to strings and then underscore or === will work.

platformInfo = _.filter(user.platforms, function (platform) {  return platform.pId.toString() === platformId;})


I tried to write a general function for that problem using underscore.js:

function findWhereObjectId(objs, comp) {    return _.find(objs, function(obj) {        return _.some(_.keys(obj), function(key) {            return (key == _.keys(comp)[0] && obj[key].equals(comp[key]));        });    });};

You could now call findWhereObjectId(user.platforms, {"pId": platformId}) and it should give you the first match.


As mentioned before, mongodb ObjectId instances do not work properly with JavaScript's equality operators.However, there's another simpler solution for this problem: You could take your MongoDB result object and convert it to a string via JSON.stringify():

    var myString = JSON.stringify(MONGODB_RESULT);

After that you can convert that string back to an object via JSON.parse():

    var myObject = JSON.parse(myString);

You can now perform any Lodash/Underscore operation on that object.

Hope that helps!