Can I determine if a string is a MongoDB ObjectID?

前端 未结 16 719
时光说笑
时光说笑 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:56

    The only way i found is to create a new ObjectId with the value i want to check, if the input is equal to the output, the id is valid :

    function validate(id) {
        var valid = false;
        try
        {
            if(id == new mongoose.Types.ObjectId(""+id))
               valid = true;
    
        }
        catch(e)
        {
           valid = false;
        }
        return valid;
    }
    
    > validate(null)
    false
    > validate(20)
    false
    > validate("abcdef")
    false
    > validate("5ad72b594c897c7c38b2bf71")
    true
    

提交回复
热议问题