如何通过将 ID 数组作为输入传递到 Google 数据存储区来检索实体?
How to retrieve entities by passing array of IDs as input in Google datastore?
我正在尝试在数据存储中实现以下 SQL 逻辑,
SELECT * from table where id in [1,2,3,4,5]
在数据存储中实现这个,我想检索所有具有这些 ID 的对应实体作为一个数组。
let employees = []
try {
for (let id of idArray) {
const employee = await employeeRepo.getOneById(workspace, id)
employees.push(employee)
}
} catch (e) {
throw e;
}
这是函数的朴素逻辑,我正在尝试将其简化为单个查询。
您是否使用此处引用的 Node.js 库:https://cloud.google.com/datastore/docs/reference/libraries
有一个函数 get
,您可以在其中传入键数组,它将 return 实体数组。
https://googleapis.dev/nodejs/datastore/latest/Datastore.html#get
可以使用 get as mentioned in the documentation
下面是一个如何根据您的代码执行此操作的示例:
const employee1 = this.datastore.key(['Employee', 1]);
const employee2 = this.datastore.key(['Employee', 2]);
const employee3 = this.datastore.key(['Employee', 3]);
const keys = [employee1, employee2, employee3];
try {
const [employees] = await datastore.get(keys);
} catch (e) {
throw e;
}
我正在尝试在数据存储中实现以下 SQL 逻辑,
SELECT * from table where id in [1,2,3,4,5]
在数据存储中实现这个,我想检索所有具有这些 ID 的对应实体作为一个数组。
let employees = []
try {
for (let id of idArray) {
const employee = await employeeRepo.getOneById(workspace, id)
employees.push(employee)
}
} catch (e) {
throw e;
}
这是函数的朴素逻辑,我正在尝试将其简化为单个查询。
您是否使用此处引用的 Node.js 库:https://cloud.google.com/datastore/docs/reference/libraries
有一个函数 get
,您可以在其中传入键数组,它将 return 实体数组。
https://googleapis.dev/nodejs/datastore/latest/Datastore.html#get
可以使用 get as mentioned in the documentation
下面是一个如何根据您的代码执行此操作的示例:
const employee1 = this.datastore.key(['Employee', 1]);
const employee2 = this.datastore.key(['Employee', 2]);
const employee3 = this.datastore.key(['Employee', 3]);
const keys = [employee1, employee2, employee3];
try {
const [employees] = await datastore.get(keys);
} catch (e) {
throw e;
}