Hey, is there a way to default to a value when a field is missing in the document itself.
So basically, I have a list of strings and this may be null for certain documents (because this field was added afterwards) and in this case I want to just default to the already assigned value, but the MongoDB Driver automatically overrides the value to null. Is there a way to achieve this?
[BsonElement("disabled_commands")] public List<string> MyList{ get; set; } = new List<string>();
You can utilise SetDefaultValue() to assign a value to a field if the document does not have a value for the field (null is a value) during deserialisation.
For example if you have the following document stored in the database :
{
"_id": ObjectId("5f583cc562d0ce4a58c7da08"),
"Name": "X"
}
With class mapping example as below:
public class MyClass
{
[BsonId]
private ObjectId Id {get; set;}
public string Name {get; set;}
public List<string> MyList {get; set;}
}
You can register and set a default value for deserialisation as below:
Without knowing more of the context, you could also declare a constructor the class. This should help defined a default value before inserting to the database. For example:
public class MyClass
{
[BsonId]
private ObjectId Id {get; set;}
public string Name {get; set;}
public List<string> MyList {get; set;}
public MyClass ()
{
Name = "";
MyList = new List<string>();
}
}