我对Google Cloud Datastore不熟悉,并且正在从NodeJS下的文档和测试中学习。
datastore.save([ entity ], (error, apiResponse) =>
{
console.log('---', key);
console.log('---', error);
console.log('---', apiResponse);
datastore.get(key).then(([entity]) =>
{
console.log('+++', entity);
console.log('+++', entity[DatastoreClient.KEY] === key);
let query = datastore.createQuery(kind).filter('__key__', '=', datastore.key(kind));
datastore.runQuery(query).then(([entity]) =>
{
console.log('...', entity);
}).catch(console.log).then(() =>
{
done();
});
});
});
控制台中保存的实体输出类似于
{
a: 'Aa',
z: 'Zz',
[Symbol(KEY)]: Key {
namespace: undefined,
id: '30',
kind: 'mch-gw/healthz/jgtdjd6h',
path: [Getter]
}
}
当我运行查询时,也会发生几行,我得到了
Error: 3 INVALID_ARGUMENT: Key path element must not be incomplete: [mch-gw/healthz/jgtdjd6h: ]
我明白我的钥匙不一定是不完整的,但如何避免?
正如您可以看到保存的entoty的上述输出,有一个id
字段,其值为'30'
。
我希望能够按id
生成的值进行搜索。
提前感谢所有人!!
答案 0 :(得分:2)
无需查询,因为kind
和id
已知
datastore.save([ entity ], (error, apiResponse) =>
{
console.log('---', key);
console.log('---', key.path);
console.log('---', error);
console.log('---', apiResponse);
const id = apiResponse[0].mutationResults[0].key.path[0].id;
// note however, that if the entity is to be updated: ie it already have
// entity[DatastoreClient.KEY] as a complete key, then
// null === apiResponse[0].mutationResults[0].key;
// also note that this `id` value need to be parsed as int...
// since it is auto-generated by google-cloud-storage engine
// and YES, even though output of entity seems to show it as a string
// it costed me 06h testing à vue, stumbling and messing in order to figure it out, so beware
const _key = datastore.key([kind, +id]);
datastore.get(_key).then(([entity]) =>
{
console.log('+++', entity);
}, console.log).then(done);
});
获取输出是预期的
{
a: 'Aa',
z: 'Zz',
[Symbol(KEY)]: Key {
namespace: undefined,
id: '42',
kind: 'mch-gw/healthz/jgtdjd6h',
path: [Getter]
}
}