Google Cloud Datastore:在一个交易中查找和更新

时间:2018-02-20 21:55:47

标签: node.js google-cloud-datastore google-cloud-sdk

我正在跟踪任务示例后的Google documentation以及Github示例中的Cloud Datastore示例。我正在尝试进行单个函数调用,并通过查找说明任务来完成任务。

function markDoneByDesc(queryString) {
  const query = datastore
    .createQuery('Task')
    .filter('description', '=', queryString);
  var taskKeyId;

  datastore
  .runQuery(query)
  .then(results => {
    const tasks = results[0];

    console.log('Task found:', tasks[0]);
    // I realize there might be multiple tasks with the same desc,
    // but I want to update just one for now
    taskKeyId = tasks[0][datastore.KEY].id;
    console.log('Saving the task Key ID', taskKeyId);
    return taskKeyId;
  })
  .then((taskKeyId) => {
    console.log('Calling markDone with task Key ID', taskKeyId);
    markDone(taskKeyId); // From the original function in the sample
    console.log('Updated task');
  })
  .catch(err => {
    console.error('ERROR:', err);
  });
}

目前,更新不会发生:(

1 个答案:

答案 0 :(得分:1)

我找到了解决方案,感谢@callmehiphop的帮助!

看起来我需要将数据存储区查询中返回的taskKeyId转换为整数,然后将其传递给markDone()函数。否则,它将作为字符串传递,并且该ID Key的查找失败。

这是正确的代码应该是什么样子(注意第一个return语句中的parseInt()):

function markDoneByDesc(queryString) {
  const query = datastore
    .createQuery('Task')
    .filter('description', '=', queryString);
  var taskKeyId;

  datastore
  .runQuery(query)
  .then(results => {
    const tasks = results[0];

    console.log('Task found:', tasks[0]);
    // I realize there might be multiple tasks with the same desc,
    // but I want to update just one for now
    taskKeyId = tasks[0][datastore.KEY].id;
    console.log('Saving the task Key ID', taskKeyId);
    return parseInt(taskKeyId,10);
  })
  .then((taskKeyId) => {
    console.log('Calling markDone with task Key ID', taskKeyId);
    markDone(taskKeyId); // From the original function in the sample
    console.log('Updated task');
  })
  .catch(err => {
    console.error('ERROR:', err);
  });
}