Can I determine if a string is a MongoDB ObjectID?

前端 未结 16 686
时光说笑
时光说笑 2020-11-30 00:31

I am doing MongoDB lookups by converting a string to BSON. Is there a way for me to determine if the string I have is a valid ObjectID for Mongo before doing the conversion?

16条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 00:46

    It took me a while to get a valid solution as the one proposed by @Andy Macleod of comparing objectId value with its own string was crashing the Express.js server on:

    var view_task_id_temp=new mongodb.ObjectID("invalid_id_string"); //this crashed
    

    I just used a simple try catch to solve this.

    var mongodb = require('mongodb');
    var id_error=false;
    try{
        var x=new mongodb.ObjectID("57d9a8b310b45a383a74df93");
        console.log("x="+JSON.stringify(x));
    }catch(err){
        console.log("error="+err);
        id_error=true;
    }
    
    if(id_error==false){
       // Do stuff here
    }
    

提交回复
热议问题