创建子记录时引发无效密钥消息 [英] Getting Invalid Key message thrown when creating child records
问题描述
使用帐户的父键时,保存programs
记录时遇到问题.
I am having problems saving programs
records when using a parent key for the account.
此代码失败,并显示错误无效密钥"(完整信息请参见底部):
This code fails with error "invalid key" (see bottom for complete):
key := datastore.NewIncompleteKey(ctx, "programs", actKey)
_, err = datastore.Put(ctx, key, &Program{Name: names[i]})
通过:
key := datastore.NewIncompleteKey(ctx, "programs", nil)
_, err = datastore.Put(ctx, key, &Program{Name: names[i]})
完整代码:
// insert test account
actKey := datastore.NewIncompleteKey(ctx, "accounts", nil)
_, err = datastore.Put(ctx, actKey, &Account{Name: "Chris Olsenio"})
if err != nil {
log.Errorf(ctx, "Insert test account %v", err.Error())
c.AbortWithError(http.StatusInternalServerError, err)
return
}
var names = []string {"Low Impact", "Running"}
for i := 0; i < len(names); i++ {
key := datastore.NewIncompleteKey(ctx, "programs", actKey)
_, err = datastore.Put(ctx, key, &Program{Name: names[i]})
if err != nil {
log.Errorf(ctx, "Insert test programs %v", err.Error())
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}
推荐答案
问题是,当您创建不完整的密钥时:
The problem is that when you create an incomplete key:
actKey := datastore.NewIncompleteKey(ctx, "accounts", nil)
您用来保存实体的时间:
Which you use to save an entity:
_, err = datastore.Put(ctx, actKey, &Account{Name: "Chris Olsenio"})
它可以工作,但是请注意,如果传递的密钥是不完整的密钥(在您的情况下),则datastore.Put()
返回由数据存储区生成的新的唯一密钥.您不存储返回的新密钥,但是应该存储!
It works, but note that if the key passed is an incomplete key (it is in your case), datastore.Put()
returns a new, unique key generated by the datastore. You don't store the returned new key, but you should!
当您尝试创建和保存"programs"
实体时:
When you try to create and save "programs"
entities:
key := datastore.NewIncompleteKey(ctx, "programs", actKey)
datastore.NewIncompleteKey()
期望nil
父密钥,如果提供的话,它必须是完整密钥(不能不完整).您传递的是不完整的密钥actKey
,因此是"invalid key"
错误消息.
datastore.NewIncompleteKey()
expects either a nil
parent key, of if it is provided, it must be a complete key (cannot be incomplete). You pass actKey
which is an incomplete key, hence the "invalid key"
error message.
解决方案很简单:存储生成的新密钥,并将新的完整密钥作为父密钥传递:
Solution is simple: store the generated new key, and pass the new, complete key as the parent key:
actKey := datastore.NewIncompleteKey(ctx, "accounts", nil)
actKey, err = datastore.Put(ctx, actKey, &Account{Name: "Chris Olsenio"})
如果err
是nil
,则actKey
现在将是完整密钥,因此在使用datastore.NewIncompleteKey()
或datastore.NewKey()
创建其他密钥时可以用作父密钥.
If err
is nil
, actKey
will now be a complete key and therefore can be used as parent key when creating other keys with datastore.NewIncompleteKey()
or datastore.NewKey()
.
这篇关于创建子记录时引发无效密钥消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!