【问题标题】:GAE Go datastore - ignoring some variables?GAE Go 数据存储 - 忽略一些变量?
【发布时间】:2015-04-30 21:42:22
【问题描述】:

假设我首先将此结构保存到数据存储中:

type Foo struct {
    Important string
    NotImportant string
}

但后来我决定不再关心NotImportant,并想停止支持它。问题是,我的数据存储区已经填充了数据,我不能只删除它并用更新的结构替换整个数据库。我知道可以创建像 Load(c <-chan datastore.Property) error { 这样的自定义加载和保存方法,但这需要在大型结构上付出很多努力。

是否有一些简单的方法可以告诉 Google App Engine Go 数据存储区在保存时忽略某些变量,而不是抱怨我正在将数据加载到的结构中没有我不再关心的变量?

【问题讨论】:

    标签: database google-app-engine go data-structures google-cloud-datastore


    【解决方案1】:

    请看这里:https://cloud.google.com/appengine/docs/go/datastore/reference 特别是关于属性的部分。

    type Foo struct {
        Important string
        NotImportant string `datastore:"-"`
    }
    

    datastore:"-" 位称为结构标记。它们允许您指定有关结构字段的元数据。 “-”表示忽略此字段。 Go 规范在这里讨论它们:https://golang.org/ref/spec#Struct_types

    encoding/json 包(和许多其他包)有类似的标签。

    【讨论】:

    • 嗯,我认为当将旧数据加载到新结构中时,这仍然会导致问题 - datastore: cannot load field "NotImportant" into a "Foo": no such struct field
    • 嗯,omitempty 标志会起作用吗,类似于 json 包的作用?
    【解决方案2】:

    你可以这样做

    if err != nil && err != err.(*datastore.ErrFieldMismatch) {         
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 2023-03-25
      • 2022-10-07
      • 2012-08-12
      • 1970-01-01
      相关资源
      最近更新 更多