which is best for performance while referring using _id? While retrieving using _id, i am getting error INVALID OBJECT ID

How should i refer a collection in another collection , a unique username or default _id (object id) or a normal id that increments when a new record is inserted . I read that object ids increase performance in mongoose , but i am unable to retrieve records using _ids as its giving error INVALID OBJECT ID . i am not getting error when retrieving using other keys like username . But as _id increases performance i am trying to use that .

  Model.find({_id : "idstring"})

I tried these 2 ways while defining schema ,

1) no definition for _id , as it will be created automatically

2) i defined _id like this : _id : { type : Schema.ObjectId }

In both ways, i am getting error "invalid object id" when retrieving records

thanks

You need to create an ObjectID from the string

 var ObjectId = require('mongoose').Types.ObjectId;
 var myObjectId = ObjectId.fromString('myhexstring');

both 1) and 2) do the same thing. its better to choose 1) and let mongoose do it for you.

i dunno about performance necessarily. the _id field just gets uniquely indexed by mongodb for you so the perf gain in queries would be due to that. you can always index whatever other fields you want if your query is slow. its easier to use _id for sure.

the INVALID OBJECT ID error is due to something being passed that cannot be cast to an ObjectId by mongoose. you can pass a hex string or an instance of mongoose.Types.ObjectId. the hex string should be 24 chars in length. double check this value.

also, explicitly casting the string to an ObjectId is done for you so there is no need to do it manually.