Can I determine if a string is a MongoDB ObjectID?

前端 未结 16 668
时光说笑
时光说笑 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 01:08

    Here is some code I have written based on @andy-macleod's answer.

    It can take either an int or string or ObjectId and returns a valid ObjectId if the passed value is valid or null if it is invalid:

    var ObjectId= require('mongoose').Types.ObjectId;
    
    function toObjectId(id) {
    
        var stringId = id.toString().toLowerCase();
    
        if (!ObjectId.isValid(stringId)) {
            return null;
        }
    
        var result = new ObjectId(stringId);
        if (result.toString() != stringId) {
            return null;
        }
    
        return result;
    }
    

提交回复
热议问题