Mongoose: How can I create a valid mongoose.Types.ObjectId?

I am testing a module of code that has a dependency on Mongoose models. I would like to check that the function was passed with a valid ObjectId as an argument. I read that new ObjectId objects can be instantiated with:

 var id = mongoose.Types.ObjectId();

      

However, the following will always return false:

var id = mongoose.Types.ObjectId();
mongoose.Types.ObjectId.isValid(id) //false

      

Why is this? Is it because I am creating a new ObjectId instance without a key? Looking at the Mongoose source, I can see that mongoose.Types.ObjectId.isValid is actually defined in its own mongo module. I'll keep digging into the driver, but if someone can tell me why this is happening, I would appreciate the time savings: p

Thank!

+3


source to share


1 answer


isValid

is a poorly documented method of the BSON class ObjectID

in the native driver.

If you look at the source for this method, you can see that it expects a string to be passed, so you need to call it like this:

mongoose.Types.ObjectId.isValid(id.toString())

      



However, as @HMR points out in the comments, the implementation isValid

has the odd quirk of assuming any 12 character string will be valid. See source .

So, unfortunately, it is best to implement validation using an approach such as:

if (id.toString().match(/^[0-9a-fA-F]{24}$/)) {
  // It a valid ObjectId
}

      

+4


source







All Articles