3

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);
});
swogger
  • 1,079
  • 14
  • 30
  • And what's `hexString`? ObjectId generally accepts hexadecimal strings ? – adeneo Apr 28 '15 at 16:43
  • 2
    I would venture to guess that your problem isn't that `campaign` is null, but rather that it's returning an array and you're trying to access the properties of the document against the array, not a single document. Change your query to use `findById`. If that's not the case, what's the value of `id` before the query is executed? – Brian Shamblen Apr 28 '15 at 17:56
  • returns empty array. Tired find one and findById still no success. – swogger Apr 29 '15 at 10:20
  • @adeneo - hex string: '553f8a4286f5c759f36f8e5b' – swogger Apr 29 '15 at 10:21

1 Answers1

6

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);
});
Brian Shamblen
  • 4,653
  • 1
  • 23
  • 37