azure CosmosDB资源未定义

qv7cva1a  于 2023-02-25  发布在  其他
关注(0)|答案(1)|浏览(114)

我可以在Cosmos上存储文档,没有问题。但是我不能使用"读取"方法检索它们

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));

图纸x1月1x
我做错了什么?
UPDATE:statusCode为404,但数据库中存在该对象。

ylamdve6

ylamdve61#

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

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>();

相关问题