英文:
GAE Go datastore - ignoring some variables?
问题
假设我开始将这个结构保存到数据存储中:
type Foo struct {
Important string
NotImportant string
}
但后来我决定我不再关心 NotImportant
,并且希望停止支持它。问题是,我的数据存储已经填充了数据,我不能只是删除它并用更新后的结构替换整个数据库。我知道可以创建自定义的 Load 和 Save 方法,例如 Load(c <-chan datastore.Property) error {
,但这需要在一个大的结构上付出很多努力。
有没有一种简单的方法告诉 Google App Engine Go 数据存储在保存时忽略某些变量,并且不会抱怨我加载数据的结构不再具有我不再关心的变量?
英文:
Say I start by saving this structure into datastore:
type Foo struct {
Important string
NotImportant string
}
But later I decide that I don't really care for NotImportant
anymore and would like to stop supporting it. The problem is, my datastore is already populated with data and I can't just drop it and replace the entire database with an updated structure. I know it is possible to create custom Load and Save methods like Load(c <-chan datastore.Property) error {
, but that would require a lot of effort on a large struct.
Is there some easy way to tell Google App Engine Go datastore to ignore some variable when saving and not complain that the structure I'm loading the data into doesn't have the variable I don't care about any more?
答案1
得分: 7
你可以这样做:
if err != nil && err != err.(*datastore.ErrFieldMismatch) {
}
英文:
You could do that
if err != nil && err != err.(*datastore.ErrFieldMismatch) {
}
答案2
得分: 3
请看这里: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包(以及许多其他包)也有类似的标签。
英文:
See here: https://cloud.google.com/appengine/docs/go/datastore/reference
Specifically the section on Properties.
type Foo struct {
Important string
NotImportant string `datastore:"-"`
}
That datastore:"-"
bit is called a struct tag. They allow you to specify metadata about struct fields. A "-" means ignore this field. The Go spec discusses them here: https://golang.org/ref/spec#Struct_types
The encoding/json package (and many others) have similar tags.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论