3

I have a collection of BsonDocuments, for example:

MongoCollection<BsonDocument> products;

When I do inserts into the collection, I want the member name to always be lowercase. After reading the documentation, it appears that ConventionPack is the way to go. So, I've defined one like this:

    public class LowerCaseElementNameConvention : IMemberMapConvention
{
    public void Apply(BsonMemberMap memberMap)
    {
        memberMap.SetElementName(memberMap.MemberName.ToLower());
    }

    public string Name
    {
        get { throw new NotImplementedException(); }
    }
}

And right after I get my collection instance I register the convention like this:

        var pack = new ConventionPack();
        pack.Add(new LowerCaseElementNameConvention());
        ConventionRegistry.Register(
            "Product Catalog Conventions",
            pack,
            t => true);

Unfortunately, this has zero effect on what is stored in my collection. I debugged it and found that the Apply method is never called.

What do I need to do differently to get my convention to work?

jared
  • 5,369
  • 2
  • 21
  • 24
Rick Rainey
  • 11,096
  • 4
  • 30
  • 48
  • 1
    Which driver are you using? Seems like a driver-specific question. Looks like C#, but I could be wrong. I'd recommending adding tags for the language/driver to attract the right readers. – jared Apr 13 '13 at 00:05
  • Yes, it is the C# driver (v1.8). – Rick Rainey Apr 13 '13 at 00:11
  • Cool, I just retagged it for you. We'll see if that attracts some folks knowledgeable in the C# driver. – jared Apr 13 '13 at 00:14
  • Thanks. It's looking more like this is just not possible for BsonDocument collections. Hopefully I'm just missing something. Since getting BsonElements by name from the BsonDocument doesn't support case-insensitive search, trying to find an element after it is saved is turning out to be very difficult. – Rick Rainey Apr 13 '13 at 03:00
  • Are you calling this before any BsonClassMap? – Alex Apr 20 '13 at 03:25
  • Can you include the code for how you call `GetCollection` and whether or not you're using class maps? – Avish May 16 '13 at 15:01

3 Answers3

2

In order to use IMemeberMapConvention, you must make sure to declare your conventions before the mapping process takes place. Or optionally drop existing mappings and create new ones.

For example, the following is the correct order to apply a convention:

        // first: create the conventions
        var myConventions = new ConventionPack();
        myConventions.Add(new FooConvention());

        ConventionRegistry.Register(
           "My Custom Conventions",
           myConventions,
           t => true);

        // only then apply the mapping
        BsonClassMap.RegisterClassMap<Foo>(cm =>
        {
            cm.AutoMap();
        });

        // finally save 
        collection.RemoveAll();
        collection.InsertBatch(new Foo[]
                               {
                                   new Foo() {Text = "Hello world!"},
                                   new Foo() {Text = "Hello world!"},
                                   new Foo() {Text = "Hello world!"},
                               });

Here's how this sample convention was defined:

public class FooConvention : IMemberMapConvention

    private string _name = "FooConvention";

    #region Implementation of IConvention

    public string Name
    {
        get { return _name; }
        private set { _name = value; }
    }

    public void Apply(BsonMemberMap memberMap)
    {
        if (memberMap.MemberName == "Text")
        {
            memberMap.SetElementName("NotText");
        }
    }

    #endregion
}

These are the results that came out when I ran this sample. You could see the Text property ended up being saved as "NotText":

Print out of Foos table with NotText properties

Ken Egozi
  • 1,825
  • 11
  • 14
JustinAngel
  • 16,082
  • 3
  • 44
  • 73
  • This example using custom `Foo` class. I think OP was asking collection of `BsonDocument`. I am having the same issue and wanted to know if convention pack even work with collection of `BsonDocument` – LP13 Jun 22 '18 at 15:48
1

If I understand correctly, conventions are only applied when auto-mapping. If you have a classmap, you need to explicitly call AutoMap() to use conventions. Then you can modify the automapping, e.g.:

public class MyThingyMap : BsonClassMap<MyThingy>
{
    public MyThingyMap()
    {
        // Use conventions to auto-map
        AutoMap(); 

        // Customize automapping for specific cases
        GetMemberMap(x => x.SomeProperty).SetElementName("sp"); 
        UnmapMember(x => x.SomePropertyToIgnore);
    }
}

If you don't include a class map, I think the default is to just use automapping, in which case your convention should apply. Make sure you're registering the convention before calling GetCollection<T>.

Avish
  • 4,516
  • 19
  • 28
0

You can define ConventionPack which is also part of their official document on Serialization. Like below which stores are property names as camel case. You can place while Configuring services/repositories

Official link https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/[Mongo Db Serialization C#]1

            // For MongoDb Conventions
            var pack = new ConventionPack
            {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register(nameof(CamelCaseElementNameConvention), pack, _ => true);