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
You can’t use
_.intersectionwith arrays ofObjectIds in this case becauseintersectionuses simple reference equality to compare the elements, rather than comparing their contents. To compare twoObjectIds for equality you need to use theObjectId.equalsmethod.So the simplest solution would be to convert the arrays to strings so that
intersectionwill work. I know you said you tried that, but you probably had a bug somewhere as that does work.