dongnianwo8289 2016-04-21 07:09
浏览 5
已采纳

创建子记录时引发无效密钥消息

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条回答 默认 最新

  • drbxr86044 2016-04-21 07:23
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)