Mongoose: Test if an arbitrary object is an ObjectId

Created on 1 Jun 2014  路  2Comments  路  Source: Automattic/mongoose

Is there an official way of testing if an object is an ObjectId? Currently, I'm using o.constructor.name === "ObjectId". I can't seem to find anything in the docs or using google, but I just wanted to check if there's an official method or something I am missing.

Thanks

Most helpful comment

You should be able to use o instanceof mongoose.Types.ObjectId

All 2 comments

You should be able to use o instanceof mongoose.Types.ObjectId

I see, yes that works. I had tried that against mongoose.Schema.Types.ObjectId but never tried mongoose.Types.ObjectId

The former fails when you test values from a callback such as in

model.save(function(err,d){
    d._id instanceof mongoose.Schema.Types.ObjectId //false
})
Was this page helpful?
0 / 5 - 0 ratings