我正在尝试保留实体,并允许数据库生成密钥。不幸的是,我似乎无法从API中挑逗合成ID。这是我正在做的事情:case "POST": d,_ := ioutil.ReadAll( r.Body) participant := new(Participant) err := json.Unmarshal( d, &participant) if err != nil { serveError( c, w, err) return } var key *datastore.Key; if participant.ID == 0 { // no id yet .. create an incomplete key and allow the db to create one. key = datastore.NewIncompleteKey( c, "participant", parentKey) } else { // we have an id. use that to update key = datastore.NewKey( c, "participant", "", participant.ID, parentKey) } // PERSIST! putKey, e := datastore.Put( c, key, participant) if e != nil { serveError( c, w, e) return } // Fetch back out of the database, presumably with my new ID if e = datastore.Get( c, putKey, participant); e != nil { serveError( c, w, e) return } // send to the consumer json,_ := json.Marshal( participant) w.Write( json)好吧,奇怪的是,ID始终为零!详细信息将保留下来,但是我使用相同的ID字段保留了多个值。对于咧嘴笑,这是对象定义:type Participant struct { ID int64 LastName string FirstName string Birthdate string Email string Cell string}接着执行GET操作,向我提供了一个实体列表(是的,我创建的实体,创建的次数与创建的次数相同),且所有ID均为零。[ {"ID":0,"LastName":"Schmuck","FirstName":"Joe","Birthdate":"12-12-12","Email":"","Cell":""}, {"ID":0,"LastName":"Schmuck","FirstName":"Jane","Birthdate":"12-12-12","Email":"","Cell":""}, {"ID":0,"LastName":"Schmuck","FirstName":"Jane","Birthdate":"12-12-12","Email":"","Cell":""}, {"ID":0,"LastName":"Schmuck","FirstName":"Jane","Birthdate":"12-12-12","Email":"","Cell":""}, {"ID":0,"LastName":"Schmuck","FirstName":"Jane","Birthdate":"12-12-12","Email":"","Cell":""}, {"ID":0,"LastName":"Schmuck","FirstName":"Jane","Birthdate":"12-12-12","Email":"","Cell":""}]为了完整起见,我还尝试过使用ID值为零的NewKey(),但这给出了相同的结果。有关NewKey的API文档说了一些有关(字符串)名称和ID均为零的信息,从而创建了不完整的密钥-我不确定如何将字符串设为零,但nil不起作用。有人帮我弄清楚,一旦指出了文档的正确部分,那么可能会出乎意料的明显。
2 回答
- 2 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消