【问题标题】:How can I get single item using id from the container in CosmosDb如何使用 CosmosDb 中容器中的 id 获取单个项目
【发布时间】:2021-07-27 03:39:21
【问题描述】:

正如标题所解释的,我想使用 id 获取项目。 现在我已经设置了 GET API,它返回 Cosmos DB 中容器内的所有文档。 现在我要做的是设置将使用特定 ID 并返回该 ID 的文档的 GET API。

这是我尝试过的..

app.get('/:id', async (req, res) => {

    try {
        const dbResponse = await cosmosClient.databases.createIfNotExists({
            id: databaseId
        });
        let database = dbResponse.database;
    
        const { container } = await database.containers.createIfNotExists({id: containerId});

        // const querySpec = {
        //     query: "SELECT * FROM c WHERE c.id = 4040c"
        //   };


        const result = await (database.container.items.id);
        console.log(result);
        
    } catch (error) {
        
        console.log(error);
        res.status(500).send("Error with database query: " + error.body);
        
    }

})

使用 database.container.items.id 给我错误“TypeError: Cannot read property 'id' of undefined”

我在 postman 中使用以下路由运行 GET 方法:localhost:3000/4040c。 其中 4040c 是存储在数据库中的文档的实际 id。

现在我正在考虑使用 SQL 查询,但我不确定该怎么做,或者即使它是正确的方法。 非常感谢任何提示或指导。谢谢。

【问题讨论】:

    标签: api express postman azure-sql-database azure-cosmosdb


    【解决方案1】:

    在文档资源上使用 GET 方法。

        https://{databaseaccount}.documents.azure.com/dbs/{db-id}/colls/{coll-id}/docs/{doc-id}
    

    如果这是一个分区容器,您需要在标头中传递分区键值。您可以在Data Plane REST API docs

    中获得完整的语法和示例

    【讨论】:

    • 好的,现在试试这个
    【解决方案2】:

    如果您知道项目的 id 和分区键值,请尝试以下操作:

    const item = container.item('item-id', 'item-partition-key-value');
    const result = await item.read();
    const itemDetails = result.resource;
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2021-10-19
      • 2015-08-26
      • 2022-06-15
      相关资源
      最近更新 更多