I currently have this basic JS code:
//Set up key, id for datastore request
const id = questionArray[q].id;
const key = ds.key([kind, Number(id)]);
//Create update entity
const modifiedQuestion = {
key: key,
data: {
position: 5,
modifiedAt: new Date().toJSON(),
}
};
let result = await datastore.update(modifiedQuestion);
There is a lot of data stored in the question entity besides "position" and "modifiedAt", but when I run the last line all the data in Datastore gets wiped except for the previous two attributes.
This doesn't exactly seem like an update to me and the documentation for datastore Node.js library is confusing to say the least. Any help would be appreciated!
Per https://cloud.google.com/datastore/docs/concepts/entities#updating_an_entity , using update()
requires you to send the whole object. So, by using update()
with only the attributes you want changed, it is modifying the existing entity to include only the attributes you sent.
You should fetch the entire existing object first, then modify it to include the attributes you wish to change, and send the whole object back when you call update()
.
The difference between update()
and save()
is that save()
decides on its own whether to do an upsert, insert, or update depending on the Key
you give it. Either way, with an existing object, you should send all the attributes, not just those that you want to change. See https://cloud.google.com/nodejs/docs/reference/datastore/latest/datastore/datastore#_google_cloud_datastore_Datastore_update_member_1_ for the details.