Comparing Mongoose Document Id's with String equivalent
Amazingly, Mongoose has the ability to generate objects that appear as strings, strings that appear as arrays, and all sorts of weirdness that you cannot see readily in console.
Luckily with some experience you learn this the hard way.
Save yourself time and use .lean()
in your read-only queries, then you will actually be able to compare 'abc'
and 'abc'
with ==
or ===
otherwise you may find this impossible.
When not using .lean()
because you want to preserve virtuals, getters, setters and save functionality on the Mongoose document, then you must convert the type.
For some keys you can use Mongoose' built in getter
get('somekey', String)
where you explicitly state the type you wish to return. This however will not work for the document _id
itself.
For this you must use:
document.toString()
Update
You can also compare using the built in .equals()
method document._id.equals(some_string)
instead of using document._id === some_string
which will not work, at all, and it will frustrate you because they will log the same.