Comparing mongoose _id and strings
The three possible solutions suggested here have different use cases.
- Use
.equals
when comparing ObjectId on two mongoDocuments like this
results.userId.equals(AnotherMongoDocument._id)
- Use
.toString()
when comparing a string representation of ObjectId to an ObjectId of a mongoDocument. like this
results.userId === AnotherMongoDocument._id.toString()
converting object id to string(using toString() method) will do the job.
ObjectID
s are objects so if you just compare them with ==
you're comparing their references. If you want to compare their values you need to use the ObjectID.equals
method:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the .equals()
method. With your example, results.userId.equals(AnotherMongoDocument._id)
. The ObjectID type also has a toString()
method, if you wish to store a stringified version of the ObjectID in JSON format, or a cookie.
If you use ObjectID = require("mongodb").ObjectID
(requires the mongodb-native library) you can check if results.userId
is a valid identifier with results.userId instanceof ObjectID
.
Etc.