0

I have a simple class which has an array of documents in it. The C# objects and mappings are below.

For some reason I the MongoDB driver isn't returning the embedded collection of documents when I find a user. I can edit the collection using AddToSet and Pull.

I don't really understand why I need to explicitly map the Groups property either. I assumed it'd just work if I called cm.AutoMap().

Here's the code I'm using to load the user...

var collection = Database.GetCollection<User>(Constants.UsersCollectionName);

var builder = Builders<User>.Filter;
FilterDefinition<User> filter = builder.Eq(x => x.Id, UserId);

var result = await collection.Find(filter)
    .ToListAsync();

return result;

I've tried to add an explicit include projection for the groups property but all that lead to was me removing all the other properties and still having an empty collection.

Here's the class...

public class User
{
    public User()
    {
        Groups = new HashSet<UserGroup>();
    }

    public string Id { get; set; }

    public string Email { get; set; }

    public IEnumerable<UserGroup> Groups { get; }
}

public class UserGroup
{
    public string GroupId { get; set; }

    public string TenantId { get; set; }
}

And the mapping...

BsonClassMap.RegisterClassMap<UserGroup>(cm =>
{
    cm.AutoMap();
});

BsonClassMap.RegisterClassMap<User>(cm =>
{
    cm.AutoMap();
    cm.MapIdProperty(c => c.Id)
        .SetIdGenerator(StringObjectIdGenerator.Instance)
        .SetSerializer(new StringSerializer(BsonType.ObjectId));
    cm.MapProperty(x => x.Groups);
});

and the json from the DB...

{
    "_id" : ObjectId("556717bb10e5c4a3f831dfca"),
    "Email" : "test@test.com",
    "Groups" : [ 
        {
            "GroupId" : "5641c6da134b9006dcdc0bff",
            "TenantId" : "5567179f10e5c4a3f831dfc8"
        }
    ]
}

Edit: I've just tried it as a list of strings and it still doesn't return the result. I've also removed the explicit mapping and it's throwing an exception. Element 'Groups' does not match any field or property of class AssetStream.Model.Admin.User. Ahh, I bet it's because there's no public setter.

BenCr
  • 5,991
  • 5
  • 44
  • 68
  • Yes, you need to have a least a private setter on the property for the driver to be able to set the value. The driver does not modify a pre-existing list in place. – Craig Wilson Nov 11 '15 at 13:26
  • Ahh, okay, so I shouldn't initialise the collection in the constructor and it'll all work? – BenCr Nov 11 '15 at 14:02
  • did you ever get this issue sorted @BenCr - I am facing a similar issue upgrading to the latest version of Mongodb driver – Ctrl_Alt_Defeat Jul 12 '18 at 13:29

0 Answers0