5

I know I'm going to feel dumb at the end of this, but I've been struggling with this...

if (user._id == req.params.id) {
    console.log("match");           
} else {
    console.log("'" + user._id + "' does not match '" + req.params.id + "'");
}

This works, comparing two strings that are the same and finding a match. But my jshint tells me to use this operator === which I understand (from here) to mean that types are also checked.

Substituting the === my test fails, generating console output like;

'56e0a2085b89105924963dc3' does not match '56e0a2085b89105924963dc3'

I think the ticks ' prove that there's no whitespace on either end. That article indicates that either the types don't match or that one of the strings was created with a new String constructor, but I don't control the code that generates these. What should I do?

  1. transform them to something else to compare? ...yuck, and to what?
  2. suppress or ignore the jshint? ...that's how a lazy developer gets in trouble later
  3. debug more? ... but how? I don't even know how to log the type of an object (in JS, that seems to be a whole other long trip through language weirdness).
Community
  • 1
  • 1
user1272965
  • 2,814
  • 8
  • 29
  • 49
  • 3
    Try doing a `typeof` on both, I'm guessing one of them is an object or buffer, maybe an ObjectID or similar, as Mongo generally uses `_id` for ObjectID's – adeneo Mar 09 '16 at 22:29
  • if you realy need `===` you can do so: `if (String(user._id) === String(req.params.id)) {` – Dmitriy Mar 09 '16 at 22:34
  • Yes. typeof is a valuable hint, the two types are "objecttype" and "string". @DmitriyLoskutov, does String(x) coerce objecttype into a string? – user1272965 Mar 09 '16 at 22:35
  • MongoDB's ObjectID's has their own `toString()` method, so you should be doing `if (user._id.toString() === req.params.id) {...` – adeneo Mar 09 '16 at 22:39
  • 1
    But if `user._id` is `null` or `undefined`, you may get 'Reference Error'. But if it is MongoDB, I guess `.toString()` is enough – Dmitriy Mar 09 '16 at 22:42

1 Answers1

6

It looks like you're using mongodb to get the objectId (I'm assuming from the syntax). You should check whether user._id is actually a string instead of an "ObjectId" object. You can pause execution or just use the typeof operator to see if user._id is actually a string.

teaflavored
  • 440
  • 4
  • 9
  • Thanks. You're right. Different types. I didn't realize that ObjectId was a thing. What's the right way to get the string version of an object id? – user1272965 Mar 09 '16 at 22:36
  • Ah.. Found it! https://docs.mongodb.org/manual/reference/method/ObjectId.toString/ Thanks very much! SO says I must wait 4 mins to accept. – user1272965 Mar 09 '16 at 22:37