node.js – Comparing mongoose _id and strings
node.js – Comparing mongoose _id and strings
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.
ObjectID
s are objects so if you just compare them with ==
youre comparing their references. If you want to compare their values you need to use the ObjectID.equals
method:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
node.js – Comparing mongoose _id and strings
converting object id to string(using toString() method) will do the job.
Related posts:
- javascript – Comparing Express User with Mongoose Foreign Key
- mongoose – Comparing number values as strings in MongoDb
- arrays – Javascript Binary Search/Insertion Preformance
- node.js – What is the correct way to do .has(), .get() and .set() for javascript Map() used in an ExpressJS server?
- node.js – How to implement data encryption at rest for MongoDB Community Edition?
- mongoose – How should I store boolean values in mongodb?
- node.js – Comparing mongoose _id and strings