swogger
swogger

Reputation: 1119

How to create ObjectId in Mongoose 4.0.x from Hex string?

mongoose.mongo.Types.ObjectId does not have fromString or fromHexString functions. It seems that new mongoose.mongo.Types.ObjectId(hexString) does not create an object id either.

var id = new mongoose.Types.ObjectId(hexString);
db.Record.find({_id:id }, function (err, campaign){
    if(err) console.log(err);
    callback(campaign);
});

Upvotes: 3

Views: 4231

Answers (1)

Brian Shamblen
Brian Shamblen

Reputation: 4703

I finally found the method you're looking for. The mongoose.Types.ObjectId class has a static function called createFromHexString, which returns an instance of an ObjectId.

var id = mongoose.Types.ObjectId.createFromHexString(hexString);
db.Record.findOne({_id: id}, function (err, campaign){
    if(err) console.log(err);
    callback(campaign);
});

Upvotes: 6

Related Questions