0

I have an Azure function that queries a CosmosDB for the documents it contains in a collection:

module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

if (context.bindings) {
  var doc = context.bindings.inputDocument;

  context.log('Get ready');
  context.res = {status: 200, body: doc};
  context.log(context.res);
}
else {
  context.res = {
    status: 400,
    body: "Something went wrong"
  };
}
context.done();
};

This query brings back everything, where I'm just looking for a specific item to be returned. How can I refactor this to just pull back certain elements? I've tried things like using:

doc.id

Here is the json structure of the sql api configured cosmosdb:

{
 "id": "1",
 "drink": "gin_and_tonic",
 "ingredients": [
   "2 ounces gin",
   "2 lime wedges",
   "3–4 ounces tonic water"
   ],
 "directions": "Add gin to a highball glass filled with ice. Squeeze in 
lime wedges to taste, then add them to glass. Add tonic water; stir to 
combine.",
 "glass": [
   "highball",
   "hurricane"
   ],
 "image": "https://images.unsplash.com/photo-1523905491727-d82018a34d75? 
   ixlib=rb- 
     0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=52731e6d008be93fda7f5af1145eac12&auto=fo 
   rmat&fit=crop&w=750&q=80"
}

Instead of doc but this does not return anything. I'm also trying to use the @azure/cosmos npm module but it seems a bit overkill and does not seem to use the input defined in the function directly. Any ideas?

4

1 回答 1

0

var doc = context.bindings.inputDocument;输入绑定是一个文档数组,即使只有一个文档。这就是为什么doc.id不返回任何东西。

两种解决方案:

  1. 根据您的尝试过滤响应。

    var doc = context.bindings.inputDocument;
    var idArray = [];
    for (var i = 0; i < doc.length; i++) {
        idArray.push(doc[i].id);
    }   
    
    context.log('Get ready');
    context.res = {status: 200, body: idArray};
    context.log(context.res);
    
  2. 在查询中过滤。转到function.json,在 cosmosdb 的绑定中,"sqlQuery": "SELECT c.id FROM c"像这样添加

    {
      "name": "inputDocument",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "DBNAME",
      "collectionName": "COLLECTIONNAME",
      "connectionStringSetting": "CosmosDBConnectionString",
      "sqlQuery": "SELECT c.id FROM c"
    }
    

    您可以使用原始代码context.res = {status: 200, body: doc};来获取所需的项目。

于 2018-12-17T03:09:40.060 回答