Search code examples
node.jsmongodbmongooseobject-identity

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


Solution

  • You need to create an ObjectID from the string

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