我可以在 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/