Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why mocha assertion fails on mongoose.Schema.objectId?

I am asserting somewhere in mocha as :

assert.equal(model.organizationId,objId);

But i am getting the failed mocha result as :

Uncaught AssertionError: "5225777180a843d901000012" == "5225777180a843d901000012"

why it happens, when the id's are same.

And how to overcome it?

like image 335
codeofnode Avatar asked Dec 20 '22 00:12

codeofnode


1 Answers

So mongodb ObjectIds in javascript are sadly frustrating in this regard. They are distinct objects resulting in obj1 === obj2 evaluating to false even though the value they represent is identical. There are 3 options:

  1. Convert to strings before comparing. I use this a lot because it's so frustrating otherwise.

  2. Use the .equals() method they provide: assert.ok(model.organizationId.equals(objId))

  3. Write a custom comparison function that can take null, ObjectIds, or Strings and do the right thing (I've also done this)

like image 99
Peter Lyons Avatar answered Jan 08 '23 03:01

Peter Lyons