How to validate a Mongo ObjectId in .Net

Viewed 2153

I have a situation where a method needs to accept an ID, look for a value in Mongo and if it's not found, call another API to fetch the item under the assumption it doesn't exist in the local database.

The problem I am having is that the MongoID for the collection is configured as an ObjectID. When I try to lookup an invalid id, it throws this exception: "is not a valid 24 digit hex string". The ids the other API expects are not the same format. Is there a way I can check the validity of the id against Mongo before I look for it?

I know I could change the id in Mongo to a string but I would prefer not to do this for consistency with our other collections.

The collection is registered like this:

        BsonClassMap.RegisterClassMap<Foo>(cm =>
        {
            cm.AutoMap();
            cm.MapIdMember(f => f.id)
            .SetIdGenerator(StringObjectIdGenerator.Instance)
            .SetSerializer(new StringSerializer(BsonType.ObjectId))
            .SetIgnoreIfDefault(true);
        });

The lookup (that throws the exception) looks like this:

await collection.FindAsync(foo => foo.id == id);
1 Answers

Thought I'd add an answer even though it's been discussed in the comments.

You can use the ObjectId.TryParse method.

var invalidObjId = "abc";

if(ObjectId.TryParse(invalidObjId, out _))
{
   // will never enter here.
}

var validObjId = "5ebd7246d2b0d6003887a8f4";

if(ObjectId.TryParse(validObjId, out _))
{
   // We will get here.
}
Related