javascript - CosmosDB 资源未定义

标签 javascript typescript azure azure-cosmosdb

我可以在 Cosmos 上存储文档,没问题。但我无法使用“read”方法检索它们

this.cosmos = new CosmosClient({
  endpoint: ''
  key: ''
});

this.partitionKey = '/id'

this.container = this.cosmos.database('test').container('test');

type Data = {
  value: string;
} & ItemDefinition;

// read it
const { resource } = await this.container.item(key, this.partitionKey).read<Data>();

console.log('>>>', JSON.stringify(resource));

打印>>>未定义

我做错了什么?

更新:状态代码为 404,但该对象存在于数据库中。

最佳答案

分区键必须是值,而不是路径。

this.partitionKey = '/id'

这是路径。

如果您有一个 ID 为 A 的项目,那么由于您的分区键路径为 /id,因此分区键为项目中该属性的值,也是 A

let key = "A";
let pk = "A";
const { resource } = await this.container.item(key, pk).read<Data>();

例如,如果您的分区键路径是 /someOtherProperty 并且您有一个项目:

{
  "id": "A",
  "someOtherProperty": "B"
}

然后,要阅读它,您需要执行以下操作:

let key = "A";
let pk = "B";
const { resource } = await this.container.item(key, pk).read<Data>();

关于javascript - CosmosDB 资源未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75535487/

相关文章:

javascript - 我是否可以在本地存储图像来绕过 CORS 问题?

typescript:从接口(interface)创建一个[键,值类型]元组

azure - 使用 C# 以编程方式将包上传到 windows azure 网站

javascript - 在 Ext JS 中将点击事件绑定(bind)到 Tab

javascript - Aptana 3 中的 ExtJS 4 代码支持

typescript - Observable 在 Angular 2 Beta 3 中被破坏了吗?

Angular ( typescript ): How to scroll to selected element by class

azure - 在 Azure AD 中,如何通过 PowerShell 设置和读取用户的主电子邮件(例如 Set-AzureADUser 和 Get-AzureADUser)?

asp.net - 从 azure 存储下载 blob 时提示“保存”对话框

javascript - jQuery 计数具有属性的元素