Home > Net >  Redefine the bson tag in golang, how to be compatible with the fields in the database with lowercase
Redefine the bson tag in golang, how to be compatible with the fields in the database with lowercase

Time:12-12

There are many structures(There are roughly hundreds of structures, all generated automatically by a tool.) like this:

type ChatInfo struct {
    Name         string `json:"name"`
    IconFrame    uint64 `json:"iconFrame"`
}

The bson tag was forgotten, causing the field name in the database to become lowercase. Like this:

{
    "name" : "myname",
    "iconframe" :101
}

Now, I want to add the bson tag:

type ChatInfo struct {
    Name         string `json:"name" bson:"name"`
    IconFrame    uint64 `json:"iconFrame" bson:"iconFrame"`
}

But when I read the data from the database, I find that the value of the IconFrame field is 0.

I want to find a way to maintain compatibility with the original lowercase field names. Because there is a lot of data and the storage is somewhat disorganized, it is not very practical to modify the data in the database.

Thanks.

CodePudding user response:

You could implement custom BSON unmarshaling logic that decodes both iconframe and iconFrame MongoDB fields into the ChatInfo.IconFrame field, but that custom logic would run in all document decoding!

You simply don't want that unnecessary overhead. Simplest is to rename existing fields in MongoDB. You just have to run a few update operations once, and then you'll be good to go forever.

For example, to rename the iconframe field to iconFrame, use this:

db.chatinfo.updateMany(
  {"iconframe": {$exists: true}},
  {$rename: {"iconframe": "iconFrame"}}
)

(The filter part may even by empty as non-existing fields will not be updated.)

  • Related