如何使用 Node 获取数据存储中最后插入的实体的 ID?
文档说要像这样插入:
datastore.insert(entity)
.then(result) => {
// Task inserted successfully.
});
由此,检查返回的 result
对象,
我发现的唯一方法就是像这样遍历对象
result[0].mutationResults[0].key.path[0].id
这看起来脆弱且不可靠。如果将来返回的对象的结构中断,应用程序就会中断。
这是在 Node 中执行此操作的正确方法吗?
最佳答案
我相信我可能已经回答了我自己的问题。
在 then
回调中,我确实必须执行 result[0].mutationResults[0].key.path[0].id
但是,我也可以定位该实体,就像这样
const userEntity = {
email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2920200f292020612c2022" rel="noreferrer noopener nofollow">[email protected]</a>',
passwd: 'secret'
}
ds.insert(userEntity)
.then(result) => {
return userEntity.key.id
// or, result[0].mutationResults[0].key.path[0].id
}
关于node.js - 数据存储区使用 Node 获取最后插入的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535582/