Type casting to ObjectId in nodejs using mongoose

Sometime, we are unable to fetch the result from database as the object id coming from our request is of String type. So for this case, we can type cast our string parameter into ObjectId easily.

var reqId = "any_string_objectId";  // coming from http request
var ObjectID = require('mongodb').ObjectID;  requiring mongodb driver
reqId = new ObjectID(reqId);  // output ObjectID

NOTE :  Mongoose automatically typecast string id into objectId during query execution but sometime we have to manually convert into ObjectID.

Comments

Popular posts from this blog

What is MQTT protocol & its use

What the hack is Call, bind & apply

What is Provider in Angular Js?