Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter mongodb object result by ObjectId with Underscore

I have a problem combining UnderscoreJS and MongooseJS in NodeJS. I have a result of mongoose and I want filter a array

var __ = require("underscore"),
    platformInfo = __.findWhere(user.platforms, {"pId": platformId});

But pId inside user.platforms is a ObjectId and can't find. But if i make a each and compare like this all its OK:

__.each(user.platforms, function(platform){

                if(platform.pId.toString() == platformId){

                }

});

How i can find in findWhere method (one line, and cool) the same result? Thanks

like image 631
user1710825 Avatar asked Jun 16 '26 19:06

user1710825


1 Answers

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;
})
like image 107
Peter Lyons Avatar answered Jun 19 '26 07:06

Peter Lyons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!