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]})
This passes:
key := datastore.NewIncompleteKey(ctx, "programs", nil)
_, err = datastore.Put(ctx, key, &Program{Name: names[i]})
Complete code:
// 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:
Which you use to save an entity:
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!When you try to create and save
"programs"
entities:datastore.NewIncompleteKey()
expects either anil
parent key, of if it is provided, it must be a complete key (cannot be incomplete). You passactKey
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:
If
err
isnil
,actKey
will now be a complete key and therefore can be used as parent key when creating other keys withdatastore.NewIncompleteKey()
ordatastore.NewKey()
.