kidCoder
kidCoder

Reputation: 354

Automatic ID for Datastore Embedded Entity (NodeJS Client)

Related to: Automatic ID for embedded entity

I am looking to do the same thing in NodeJS as what's done in the linked post in Java, but given that there is no Entity or EmbeddedEntity type in the Node version of the library (as far as I can find), I am not sure how to do this. I am saving an array of embedded entities, each of which has 2 keys on it. I would like to be able to automatically generate a value on-save for a key, lets call it embeddedEntityKey, without worrying about generating random values in my code. Possible?

Upvotes: 0

Views: 929

Answers (1)

Artsiom Miksiuk
Artsiom Miksiuk

Reputation: 4303

I guess you confused with two terms here. In java a lot of work is done by client library, including rich datastore mapping technics. In node, there are two kinds of entities that you can store inside parent entity.

  1. You can specify a property and put object into it. In this case you will just write ordinary object into property and this wouldn't become and embeded entity. Example:

    db.save({ 
        key: db.key(["SomeKind"]), 
        data: { 
            object: {
                someVal: 1
            }
        }
    });
    
  2. You need to specify parent id in order to create true embedded entity.

    db.save({ 
        key: db.key({
            path: ["SomeParentKind", "ParentIdOrName", "EmbededEntityKind"]
        }), 
        data: {
            someVal: 1
        }
    });
    

Shortly saying, in Node.js embedded entity creation mechanism is different. Here you can find more details about working with datastore on Node.js environment. https://cloud.google.com/datastore/docs/concepts/entities#datastore-basic-entity-nodejs

Specifically, look at the ancestor section in documentation. https://cloud.google.com/datastore/docs/concepts/entities#ancestor_paths

Update 2

Save possibilities with Datastore in Node.js.

Save after get

db.get(db.key(["MyKind", db.int("123123123")]))
    .then(results => {
        let entity = results[0];
        entity.prop = 1;
        return db.save(entity);
    });

Initial save with write key into object

let object = {
    prop: 1,
    [db.KEY]: db.key(["MyKind"])
};

db.save(object);

Initial save with passing key as save argument

let object = {
    prop: 1
};

let key = db.key(["MyKind"]);

db.save({
    key: key,
    data: object
});

Upvotes: 1

Related Questions