How to check MongoDB ObjectId valid in JS?

The TLDR answer:

If you are using mongoose as your ORM layer for MongoDB in any of the NodeJS frameworks then one of the simplest and best ways I have come across is

if (!mongoose.Types.ObjectId.isValid(object_id)) {
    throw "Invalid id";
}