Home > database >  MongoDB.Driver - Convert property Array<string> to Array<ObjectId>
MongoDB.Driver - Convert property Array<string> to Array<ObjectId>

Time:11-18

.NET 6, MongoDB.Driver 2.17.1

I have given property property:

public class SecurityTreePermission
{
    ...
    // In database, this is an `ObjectId[]`
    [BsonRepresentation(BsonType.ObjectId)]  
    public string[]? Roles { get; set; } 
    ...
}

In database, it is actually an ObjectId[].

When doing a SELECT (deserialization process), the BsonRepresentation attribute works, and the field is correctly mapped from ObjectId[] -> string[].

But when doing an INSERT (serialization process), the string[] is not serialized to a ObjectId[]. Instead, the values are stored as string[].

I found the docs about some interfaces, likeIBsonSerializer but it's not quite clear.

CodePudding user response:

In this Documentation you should be able to refer to a class called "ObjectId", this should be able to be initialized with a string.

I haven't worked with it before and dont know if you can initialize it(ObjectId[]) with a string[].

If you cant; Then i would make a loop, init them as ObjectIds and then looping them into an ObjectId[].

Or maybe this would help.

CodePudding user response:

I found a workaround for now.
Though I don't find it clean, it works fine.

I keep the property with which I want to work in C# (string[]), but I BsonIgnore it. For working with the actual collection field, I use private property.

public class SecurityTreePermission
{
    ...
    [BsonIgnore]
    public IEnumerable<string>? Roles { get; set; }

    [BsonElement("roles")]
    private IEnumerable<ObjectId>? Roles_ObjectId
    {
        get
        {
            var roles_objId = new List<ObjectId>();
            if (this.Roles is not null)
                foreach (var role in this.Roles)
                    roles_objId.Add(new ObjectId(role));

            return roles_objId;
        }
        set
        {
            var roles = new List<string>();
            if (value is not null)
                foreach (var role in value)
                    roles.Add(role.ToString());

            this.Roles = roles;
        }
    }
    ...
}
  • Related