Jensen
Jensen

Reputation: 349

MongoDB Serialization Conventions ignoreifnullconvention ignores false values

I have a C# application that writes values to mongo. With it I have a convention pack

var pack = new ConventionPack();
            pack.Add(new IgnoreIfDefaultConvention(true));
            ConventionRegistry.Register(
                "Ignore if default",
                pack,
                t => x);

Writing to my database is:

var user = new UserModel{
     Name = "Willy",
     Active = false
}
mongoContext.User.InsertOne(user);

I use this to ignore missing values and avoid writing every single field in my POCO model. One of those values, Active has to have both true and false in it. But when I write the values with the Convention pack, it ignores all Active that are false.
To test it, i ran it without the convention pack and writes the values fine, but with the convention pack it does not. Is there a way to exclude a particular field or tell the convention pack to accept false values?
Thank you

Upvotes: 1

Views: 1510

Answers (1)

Naren
Naren

Reputation: 308

IgnoreIfDefaultConvention is going to ignore all default values. Use IgnoreIfNullConvention instead.

var pack = new ConventionPack();
pack.Add(new IgnoreIfNullConvention(true));
ConventionRegistry.Register("Ignore if null",pack,t => x);

Another option would be to change the UserModel to use an enum instead of boolean flag. For example, enum UserStatus { Unknown, Active, Inactive }. In this case, IgnoreIfDefault convention will ignore the default value "Unknown" but the rest of the values will be captured.

Upvotes: 1

Related Questions