Converting a hexstring to ObjectId for MongoDB in Javascript

How to convert a string value to ObjectID

Sometimes, the ObjectID of your MongoDB document is delivered as a 24 character hexstring. You can’t just compare this hexstring to an ObjectID, because the comparison will fail.

The solution is as follows:

var mongoose = require('mongoose' );
var hexstring = '58666c89d4bc6622ed5373dc';
// convert it to ObjectID
var ObjIDtype = mongoose.Types.ObjectId(hexstring);

The variable ObjIDtype now contains the value as type ObjectID and can be compared to MongoDB objectID’s.

Laat een reactie achter

Het e-mailadres wordt niet gepubliceerd.

Deze site gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.

By using this site you acknowledge the use of cookies (which are mostly harmless, btw) More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below you are agreeing to these settings.

Close