There can be only one instance, only one entity bound / denoted by the same datastore key.
And entities (bound to a key) can only be overwritten, not updated / extended / appended gradually.
So if you already have an entity saved, to update/ modify it, you have to first load it, then modify the entity in memory, and write out (save) the modified entity. This save will overwrite the existing entity in the datastore.
If for a property you want to store multiple values, the type of that property must support storing multiple values. Slices in Go are such types.
So in your example your entity should look like this:
type Entity struct {
Values []string
}
When you load an existing Entity
, you have to append the new value to its Values
field, something like this (in pseudo code):
e := ... // load existing entity
e.Values = append(e.Values, input) // Append new data to Values
// And now save Entity (e) with the same key
In code:
client, err := datastore.NewClient(ctx, projectID)
tx, err := client.NewTransaction(ctx)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
fmt.Fprint(w, input)
taskKey := datastore.NameKey("Entity", "stringID", nil)
var task Entity
if err := tx.Get(taskKey, &task); err != nil {
log.Fatalf("tx.Get: %v", err)
}
task.Values = append(task.Values, input)
if _, err := tx.Put(taskKey, &task); err != nil {
log.Fatalf("tx.Put: %v", err)
}
if _, err := tx.Commit(); err != nil {
log.Fatalf("tx.Commit: %v", err)
}
If you need to index by this Values
property, you might run into troubles if it contains many values. See this possible duplicate for more details: App Engine Datastore: How to set multiple values on a property using golang?
If you run into this problem, you should consider modeling and storing your data in a different format, e.g. saving in multiple entities, where one entity would only store a single input
, connected with the key it belongs to.