0

I the following function I am comparing two equal values ( as displayed in the console , but the return is false ...

    function removeGroup(req, res, next) {
      const user = req.user;
      const found = user.groups.some((obj, idx) => {
        console.log('obj._id: ', obj._id);
        console.log('req.params.groupId: ', req.params.groupId);
        if (obj._id === req.params.groupId) {
          console.log('equal');
          user.groups.splice(idx, 1);
          return true;
        }
        console.log('not equal');
        return false;
      });
      if (found) {
        user.save()
          .then(savedTable => res.json(savedTable))
          .catch(e => next(e));
      } else {
        res.status(404);
        res.json({ message: 'Group Not Found' });
      }
    }

Here is the console .log result

    obj._id:  59109bc44ea63331151b9327
    req.params.groupId:  59109bc44ea63331151b9327
    not equal
  • 3
    Apparently they are not equal. Check their type (using `typeof`). – Bergi May 08 '17 at 16:47
  • 1
    What @Bergi said, the difference between `==` and `===` is the they have to be the same type. If `==` returns false, then there is something else going on. – Joe Lissner May 08 '17 at 16:49
  • 1
    possible duplicate of [Comparing mongoose _id and strings](http://stackoverflow.com/q/11637353/1048572)? Unfortunately you haven't provided any info about those objects. – Bergi May 08 '17 at 16:49
  • sorry .. effectively user.groups.some((obj, idx) => {..} is referring to mongoose model. so I should use the toString() method –  May 08 '17 at 16:54

1 Answers1

0

A good practice in JavaScript is to always use === instead of == to avoid coercion (implicit type conversion). For the record, you could also use Object.is() in ES6...

So why your code is not working? It is difficult to be assertive because you did not provide enough details in your question, but from what I saw in the comments, I think you will find a clear explanation below:

obj._id and req.params.groupId must be strictly equal in terms of value and type. This is great for primitive values (strings, numbers, booleans, ...), but the problem is that, in JavaScript, you cannot compare objects like so. In this language, objects are compared by reference. This means that an object will never be equal to another if it is not the same instance, even if it has exactly the same properties.

let ref = {};

// false
console.log({} == {});
console.log({} === {});
console.log(Object.is({}, {}));

// true
console.log(ref == ref);
console.log(ref === ref);
console.log(Object.is(ref, ref));
Graham
  • 7,431
  • 18
  • 59
  • 84
Badacadabra
  • 8,043
  • 7
  • 28
  • 49