繁体   English   中英

Google数据存储区实体密钥ID是字符串而不是数字

[英]Google Datastore entity key id is a string instead of number

当我使用数字键将实体保存到数据存储区时:

datastore.save({
  key: datastore.key(['Thing', 123]),
  data: [
    { name: 'name', value: 'My thing' }
  ]
});

然后再次取回

datastore
  .createQuery('Thing')
  .filter('__key__', datastore.key(['Thing', 123]))
  .select('__key__')
  .run((err, entities) => {
    const key = entities[0][datastore.KEY];
    console.log(`key.id = ${key.id}, type = ${typeof key.id}`);
  });

输出:

 key.id = 123, type = string

但我希望它能输出:

 key.id = 123, type = number

数据存储库似乎需要花很长时间才能确保ID是一个数字 ,但随后将其作为字符串返回。 使用ID创建新密钥时,例如

const newKey = datastore.key(['Thing', key.id]);

这将返回一个无法找到任何实体的键,因为该值将被分配给name而不是id因为它是一个字符串。

我在这里做了一个小的repro案例: https : //github.com/arjenvanderende/datastore-key-id-is-string

对我来说,将ID作为字符串而不是数字返回是很奇怪的。 这是预期行为还是库中的错误?

编辑

当您拥有另一个对象的“外键”并使用key.id进行设置时,此问题将成为一个更大的问题。 例如

datastore.save({
  key: datastore.key(['Thing', 234]),
  data: [
    { name: 'name', value: 'My other thing' }
    { name: 'parentThingId', value: thing[datastore.KEY].id }
  ]
});

从数据存储中再次检索此对象后,查找其他事物的父对象将失败。 使用键datastore.key(['Thing', otherThing.parentThingId)在数据存储区中进行查找将不会产生任何结果,因为它会尝试通过name而不是id进行查找。 现在还不是很明显这是问题所在,因为类型在数据存储区控制台中有些隐藏。

它是一个字符串,但是被识别为id 当您将来使用key对象发出请求时,API会做适当的事情。

我们必须在库中进行一些特殊情况的处理,因为ID可能很长-超出了JavaScript整数允许的上限。 我们将其存储为字符串是内部构件,不应影响用户。

使用ID创建新密钥时,例如

 const newKey = datastore.key(['Thing', key.id]); 

为什么不只使用key本身而不是创建新的Key对象?

或者,您可以通过以下方式强制使用ID类型:

const newKey = datastore.key(['Thing', datastore.int(key.id)]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM