Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom serialization of enums in MongoDB

Referencing this SO question about custom serialization of strings to enums and vice versa in Json.NET, decorating the enum members using the EnumMember attribute - is there a way to get MongoDB to perform the same feat?

I have just refactored some previously string fields to enums and was wondering if there is any way to instruct Mongo to also read the EnumMember values when (de-)serializing and avoid me having to go through the database and update all the current text values.

like image 481
ultra909 Avatar asked Nov 10 '22 08:11

ultra909


1 Answers

i´m using package: PackageReference Include="MongoDB.Bson" Version="2.12.1"

my map class:

    public class OfferMap
{
    public static void Configure()
    {
        BsonClassMap.RegisterClassMap<Offer>(map => //Offer is a class
        {
            map.AutoMap();
            map.SetIgnoreExtraElements(true);

            map
            .SetIsRootClass(true);

            map
            .MapMember(x => x.OfferType)
            .SetSerializer(new EnumSerializer<OfferType>(MongoDB.Bson.BsonType.String)) // OfferType is an Enum
            .SetElementName("offerType")
            .SetIgnoreIfNull(false)
            .SetIsRequired(true);
like image 164
Felipe Augusto Avatar answered Nov 15 '22 06:11

Felipe Augusto