Handling missing document fields which are collections in mongodb c#

i have the model below in c#


public class User
{
    public string? AvatarUrl { get; set; }
    
    public int? Points { get; set; } = 0;
    
    public List<WatchSession>? WatchSessions { get; set; } = new();
}

the problem here is that not all Users in the mongodb database has WatchSessions field, now i get the error below

InvalidOperationException: Document element 'WatchSessions' is mapped collection but missing.

i tried adding [BsonIgnoreIfNull] and [BsonDefaultValue(null)] but none of these work, can you just set this to null if it’s a missing field? why do we have to go through this, in MySQL it’s being set to null and we’re good to go, I’m using Mongo EF-Core

Hi Saylent.

While we currently support individual sub-documents being missing we do not yet support collections of sub-documents (OwnsMany) being entirely missing in the document - we only support them being null.

I’m looking into what is involved in us supporting this scenario and will update the thread when I have more information.

We’ve had a discussion and given that:

  1. There is no way to tell EF that a collection is not required
  2. It would be repetitive to specify this everywhere if your model typically does this
  3. Some other providers allow this by default

We’re going to relax the rule so that missing elements that are owned collections instead default to null rather than throwing.

I’ve raised ticket https://jira.mongodb.org/browse/EF-188 to track the work.

Hi Saylent.

v8.2.3 of the MongoDB EF Core Provider has just been released which relaxes the rule on whether an element needs to exist in the Bson for an owned collection property.

If the element is missing in the Bson the collection property will be null instead of throwing on deserialization.

Hope that helps.