Start a new topic

Cannot find entity in Colllection

logger(docs._id == "547499c25aee6ffe3600e2cb"); // true

modules.collectionAccess.collection('squaduser').find({

"user._id" : "547499c25aee6ffe3600e2cb"

}, function(err, results) {

});



is working ...



logger(docs._id == "547499c25aee6ffe3600e2cb"); // true

var userID = docs._id;

modules.collectionAccess.collection('squaduser').find({

"user._id" : userID

}, function(err, results) {

});



is not working

meaning results always is empty, but the entity is there!





i really have no clue whats the problem .... any idea?


1 person has this question

I had the same problem. Casting the variable to string solved this. 


Thanks. 

Hi Nico, my guess would be that in the second case, `docs._id` is actually an instance of the MongoDB ObjectID rather than a plain string, but that the `user._id` stored in your `squaduser` collection is an actual string. Thus, when you try searching using an explicit string, the query works, and when you try using the variable value, it does not. To solve this, you should explicitly cast your `userID` variable to a string when constructing the query.



As for why your equality comparison works in both cases -- in JavaScript, double equals (`==`) casts the arguments so that they can be compared, meaning that in your second example, it will actually compare docs._id.toString() to the ID string, which evaluates to true. For this reason, you should (almost) always use triple equals (`===`) as your comparison operator, as it does not perform any casting. If my theory above is correct, then in the case of your second example, the conditional would have failed using triple equals.
Sorry for pushing this, but it's really frustrating and i can't go further with my script since this isn't working correctly. Any help would be really great. :)



best, Nico