【问题标题】:How to query from cosmosdb in azure function with typescript如何使用 typescript 从 azure 函数中的 cosmosdb 进行查询
【发布时间】:2019-11-09 22:05:48
【问题描述】:

我是 Typescript 和 CosmosDB 的新手,这可能是一个相当愚蠢的问题,但是,我在网上搜索了一整天,找不到适合我的情况的解决方案。希望有人愿意在这里提供帮助。

基本上,我尝试使用 Azure 函数(javascript/typescript)实现 RESTful API,这些 API 的作用是连接到我的 Azure cosmosdb(sql) 并从中查询。数据绑定是我用来将数据库与我的函数绑定的东西。问题是我不确定如何根据特定列值从数据库中选择值(从用户名 =“abc”的表中选择 id)。

为了让我的问题更清楚,这是我在 cosmos db 中的用户项:

{
    "id": "1",
    "userid": "33218898",
    "username": "test1",
    "password": "psw",
    "email": "1@test.com",
    "momentID": [
        "1",
        "2",
        "3"
    ],
    "followingID": [
        "2",
        "3"
    ],
    "followerID": [
        "2",
        "3"
    ]
}

这就是我从 azure 函数中获取用户的方式:

module.exports = async function (context, req, inputDocument) {
    context.log('JavaScript HTTP trigger function processed a request.');
    if (!!inputDocument && inputDocument.length > 0) {
            if(req.query.id || (req.body && req.body.id)){
                context.res = {
                    // status: 200, /* Defaults to 200 */
                    body: "User with id [" + req.query.id + "] is :" + inputDocument[req.query.id-1].username
                };
            }
            else if(req.query.name || (req.body && req.body.name)){
                const user = inputDocument.select("[@username='test1_update']");
                const userid = user.id;
                context.log('User id with username :' , userid);
            }else{
                var arr_user = new Array(inputDocument.length);

                for(var _i = 0; _i <inputDocument.length; _i++)
                {
                    arr_user[_i] = inputDocument[_i].username;
                }
                context.res = {
                    status: 200, 
                    body: "Hello " + arr_user
                };
                context.log('Username: ', arr_user);
            }
    }  
    else{
        context.log('Nothing in the inputDocument');
    }
};

似乎 select 不是 typescript 中定义的函数,有人可以帮忙吗?

【问题讨论】:

    标签: typescript azure azure-functions azure-cosmosdb


    【解决方案1】:

    您可以使用带有 javascript 的 @azure/cosmos 包从集合中读取数据。

    const CosmosClient = require("@azure/cosmos").CosmosClient;
    
    getUser: async function (login) {
        const querySpec = {
          query: 'SELECT * FROM users',
          parameters: [
          ]
        };
    
        const result = await cosmosClient
          .database(databaseId)
          .container(containerId)
          .items.query(querySpec)
          .fetchNext();
    
        if (result && result.resources) {
          return result.resources[0];
        }
    
        return undefined;
      }
    

    这是sample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 2018-10-09
      • 2018-11-07
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      相关资源
      最近更新 更多