Michael Seltenreich Michael Seltenreich - 3 months ago 11
Node.js Question

Weird comparison behavior in mongoose

What am I missing?
I am comparing 3 objects:

userID
was pulled in a model search before

req.user._id
is the session variable holding the user id

and
docs[i].toWho
points to the same id.

When I compare them I get a false negative. Why?

At first I thought the comparison fails because
docs[i].toWho
is a mongoose objectID and the others are strings, so I cast them as mongoose objectIDs.

Still, results fail. See output:

57a8d7f189d00bfc1917187e 57a8d7f189d00bfc1917187e 57a8d7f189d00bfc1917187e
false false true
false false true


code:

console.log(docs[i].toWho,req.user._id,userID)
console.log(docs[i].toWho==req.user._id,docs[i].toWho==userID,req.user._id==userID)
console.log(docs[i].toWho==mongoose.Types.ObjectId(req.user._id),docs[i].toWho==mongoose.Types.ObjectId(userID),mongoose.Types.ObjectId(req.user._id)==mongoose.Types.ObjectId(userID))


Edit:

This entire thing originated when I tried to debug an update query.

Notification.update({
toWho: req.user_id
}, {
$set: { seen: true }
}, {
multi: true
}, function (err,count) {});


And no record was updated. All the records are still showing
seen=false


Edit 2

Turns out, I had a typo in my code. I user req.user_id instead of req.user._id

Thank you Thomas

Answer

It's not a real answer because it was a mistake.

String are not allowed in querying and we have to cast it in mongoDB (thx to @str).

The mistake was a typing mistake (req.user_id => req.user._id)

But to compare ObjectId, it's easier to convert them into string and compare them with ==.

Comments