nevi_me
nevi_me

Reputation: 2730

Underscore: comparing mongoose objectIds failing

I am having trouble comparing mongoose ObjectId's or their String values.

I have two arrays, the first is:

a = [
"50dfb24123c43a501400000e",
"50d1bda330eb531c1400000d",
"50d1bdcf30eb531c1400000f",
"50d1beac30eb531c14000012",
"50dfb26223c43a501400000f"
]

and the second is:

b = [
"50dfb26223c43a501400000f"
]

running _.intersection(a,b) gives me an empty array [] instead of the value in b.

The values of a and b are _.plucked from results returned by a Mongoose model. I have tried converting each of the array values to strings, and I still get the same result of an empty array.

I searched for similar questions, but the solutions that I've found aren't helping (i.e. the conversion to strings).

Is there something I am missing? I know that the problem is the Mongoose ObjectIds because if I intersect the raw arrays as pasted above, I get the correct result.

Thanks

Upvotes: 1

Views: 2253

Answers (3)

klall
klall

Reputation: 485

In lodash4, you can now do this:

_.intersectionWith(a, b, _.isEqual)

Upvotes: 6

Nick Ma
Nick Ma

Reputation: 88

You can use _.isEqual(object, other) to test if 2 mongoose ObjectID are have same content.

for instance,

var ret=[];
_.each(b,function(x){
    ret.push(_.filter(a,function(y){
        return _.isEqual(x,y);
    }))
})

now, you should get ret contains "50dfb26223c43a501400000f" as data type of Mongoose's ObjectId.

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311835

You can't use _.intersection with arrays of ObjectIds in this case because intersection uses simple reference equality to compare the elements, rather than comparing their contents. To compare two ObjectIds for equality you need to use the ObjectId.equals method.

So the simplest solution would be to convert the arrays to strings so that intersection will work. I know you said you tried that, but you probably had a bug somewhere as that does work.

Upvotes: 1

Related Questions