Getting Invalid Key message thrown when creating c

2019-07-14 05:02发布

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
        }
    }

1条回答
闹够了就滚
2楼-- · 2019-07-14 05:29

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"})

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:

key := datastore.NewIncompleteKey(ctx, "programs", actKey)

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"})

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().

查看更多
登录 后发表回答