如何使用azure JavaScript函数应用程序在cosmos DB中插入数据?

时间:2019-12-04 10:25:35

标签: azure azure-functions azure-web-sites azure-cosmosdb azure-function-app

我正在尝试从azure javascript函数应用程序向cosmos DB插入数据。 这是function.json文件

 {
 "bindings": [
  {
  "type": "cosmosDBTrigger",
  "name": "documents",
  "direction": "in",
  "leaseCollectionName": "leases",
  "connectionStringSetting": "CosmosDBConnection",
  "databaseName": "roi",
  "collectionName": "reports",
  "createLeaseCollectionIfNotExists": "true"
  },
  {
  "type": "http",
  "direction": "out",
  "name": "res"
  }
 ]
}

index.js具有这样的代码。

module.exports = async function (context, documents) {
     if (!!documents && documents.length > 0) {
    context.log('Document Id: ', documents[0].id);
  }
 }

以下图像在应用程序中将出现错误。 enter image description here

enter image description here

enter image description here

是否有任何函数或查询可插入数据?来自api的请求数据将如下所示(它来自请求的rawBody属性)

enter image description here

当我获取数据时,它的工作正常。

{
  "name": "inputDocumentIn",
  "type": "cosmosDB",
  "databaseName": "roi",
  "collectionName": "reports",
  "sqlQuery": "SELECT * from reports r",
  "connectionStringSetting": "CosmosDBConnection",
  "direction": "in"
}

local.setting.json文件

{
"IsEncrypted": false,
"Values": {
 "AzureWebJobsStorage": "UseDevelopmentStorage=true",
 "AzureWebJobsDashboard": "",
 "FUNCTIONS_WORKER_RUNTIME": "node",
 "CosmosDBConnection": "AccountEndpoint=.....;"
 },
"Host": {
 "LocalHttpPort": 7071,
 "CORS": "*"
 }
}

在local.setting.ts文件中有这个蔚蓝的值,我得到以下错误。 enter image description here

3 个答案:

答案 0 :(得分:0)

请检查连接字符串是否指向正确的帐户,并检查它是否是由防火墙和网络引起的。在azure门户上转到您的cosmos db帐户,然后单击“防火墙和虚拟网络”。您可以选择“所有网络”或“选定的网络”,并填写当前IP。

答案 1 :(得分:0)

这听起来像一些依赖冲突。您能否在项目文件夹上执行dotnet clean,然后验证所有项目(如果您具有项目依赖项)是否具有Microsoft.Azure.WebJobs.Extensions.CosmosDB package的最新版本(当前为3.0.5)?

答案 2 :(得分:0)

上述问题的解决方案是: 我已经用此代码更改了function.json文件。

{
"bindings": [
 {
  "authLevel": "anonymous",
  "type": "httpTrigger",
  "direction": "in",
  "methods": [ "post" ],
  "name": "req"
 },
 {
  "type": "http",
  "direction": "out",
  "name": "res"
 },
 {
  "type": "cosmosDB",
  "name": "outputDocument",
  "databaseName": "roi",
  "collectionName": "reports",
  "createIfNotExists": true,
  "connectionStringSetting": "CosmosDBConnection",
  "direction": "out",
  "partitionKey": "/id"
  }
 ],
 "disabled": false
}

,来自前端的请求将被这样处理。

  module.exports =  function (context, req) {
    if (req.body) {
    context.bindings.outputDocument = req.body;
    var responseBody = {};
    responseBody.message =  "Wow! data with  id '" + req.body.id + "' was created!";

    context.res = {
        status: 201, 
        body:responseBody
    };
   }
  else {
    context.res = {
        status: 400,
        body: { "message" : "Please pass a valid  object in the request body"}
    };
  }
 context.done();
 }