0

I am using a Node.js server and async.js to handle asynchronous callbacks, as well as Mongoose to connect to my Mongo datastore. I am attempting to determine if two object _id's are equal, and if so, execute some code. However, the comparison is not executing correctly. Here's the code:

async.forEachSeries(offerItem.offers, function(currentOfferItemOffer, callback) {
    Offer.findById(currentOfferItemOffer, function(err, offerItemOffer) {
        if (err) throw err;
        console.log(offerItemOffer._id) // 56953639ea526c8352081fdd
        console.log(offer._id)          // 56953639ea526c8352081fdd
        if (offerItemOffer._id !== offer._id) {
            console.log('offerItemOffer._id !== offer._id') // Is being logged even though it shouldn't

            ....

I am very confused as to why a simple comparison like this would not be executing correctly. The code functions as desired when the two _id's are checked for equality using '===' - but this is incorrect logically, as the next block should only be executed when the _id's are not equal. Any thoughts would be greatly appreciated. Thanks!

3 Answers3

0

Use toString() method on _id.

if (offerItemOffer._id.toString() !== offer._id.toString()) {//...

console.log() calls toString() so it seems that output is the same because it is converted to string.

Michal K.
  • 179
  • 2
  • 10
0

It looks like _id are objects, not strings. In this case they are still two different object. You should do:

JSON.stringify(offerItemOffer._id) !== JSON.stringify(offer.-id) 

to compare them as strings.

More here Object comparison in JavaScript

Community
  • 1
  • 1
krl
  • 5,087
  • 4
  • 36
  • 53
0

JavaScript has two types of inequality operators. Namely != and !==.

The != calls stringify upon operators before comparison. That means that the type/class of a given operator isn't taken into account when comparing.

The !== doesn't call stringfy. That means that the type/class of an operator is taken into account.

That's why the following sentences produce distinct outputs

'1' != 1   // -> false (they are equal since what's being compared is '1' != '1'
'1' !== 1  // -> true  (they are different since what's being compared is a string with an integer)

Thus you could fix your problem by ignoring object types/classes by using the != operator.

Cristiano Mendonça
  • 1,220
  • 1
  • 10
  • 21