Orlin Bobchev
Orlin Bobchev

Reputation: 197

Updating Entity in Google Datastore using Nodejs

Is it possible to do an update of Entity, replacing only the data from the input and retaining the rest of the Entity?

Upvotes: 0

Views: 1260

Answers (2)

Orlin Bobchev
Orlin Bobchev

Reputation: 197

I've got the desired effect this way:

   transaction.run(function(err) {
    if (err) {
        res.end(err);
    }

    transaction.get(key, function(err, entity) {
        if (err) {
            res.end(err);
        }
        if (entity) {
            entity.ImportStatus = InputImportStatus;
        } else {
            res.end('No Entity err');
        }

        transaction.save({
            key: key,
            data: entity
        });

        transaction.commit(function(err) {
            if (!err) {
                res.send(`Updated`)
            } else { res.end(err); }
        });
    });
});

Upvotes: 0

Dan McGrath
Dan McGrath

Reputation: 42008

You'll want to do a transaction where you read the entity, update the value, write the entity.

function updateEntity (updateKey, newValue) {
  const transaction = datastore.transaction();

  return transaction.run()
    .then(() => transaction.get(fromKey))
    .then((result) => {
      const entity = result[0];

      entity.myProperty = newValue;

      transaction.save(
        {
          key: updateKey,
          data: entity
        }
      );

      return transaction.commit();
    })
    .catch(() => transaction.rollback());
}

Upvotes: 1

Related Questions