I'm probably missing something obvious, but I can't find a way to store a JSON object with descendants in such a way that the Datastore DB has a hierarchy of entities that can be queried. Example code:
const Datastore = require('@google-cloud/datastore');
const datastore = new Datastore({
projectId: 'MY_PROJECT_ID',
});
const ot1 = {
// The kind and ID for the new entity
key: datastore.key(['OT', '1']),
data: {
obj: [
{
var1: 'var1',
var2: 'var2',
},
{
var3: [{obj2:'var3'}, 'var5'],
var4: 'var4',
},
] // obj
} // data
};
datastore.save(ot1);
If I now check my Datastore, it contains one entity 'obj' of type Array (as expected), but the value is one big JSON blob representing the array, i.e. I cannot drill down into descendant objects (which are obj[0]
, obj[1]
, obj[1].var3
, and obj[1].var3[0]
) from the Datastore console (whereas with AWS DynamoDB, and same JSON, I am able to drill down -- as though it handles the conversion from JS objects to DB format automatically). Yet, the docs indicate that the parent of an entity cannot be changed after entity created, so the parent entity has to be created before the child entity. It seems like the API requires that I save in multiple steps:
- Save root object, with empty list
- Save each child of root, setting their parent to root (
obj
); not clear how to add each child to the array;obj[1]
would have empty Array asvar3
property value - Save each element of
obj[1].var3
array, setting their parent toobj[1]
; same issue about array
This is a lot of work, surely there is a library function that does this automatically, but I am unable to find one. And I'm not sure what this would look like in Datastore console, I suspect you would end up with 4 objects, i.e. hierarchy would only be indirectly known by observing the parent properties.
Update: I suspect the answer is to use an ORM like js-data.