【问题标题】:Azure Function with NodeJS: retrieve id generated by documentDB after a POST request带有 NodeJS 的 Azure 函数:在 POST 请求后检索 documentDB 生成的 id
【发布时间】:2018-03-26 22:34:51
【问题描述】:

我对 AzureFunction 有一个非常简单的问题。我想发出一个 POST 请求并将其发送回客户端到新创建的对象,它的 id 由 documentDB 创建。 这是我的代码的样子:

function.json

   {
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [ "post" ],
      "route": "blocks"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "block",
      "type": "documentDB",
      "direction": "out",
      "databaseName": "digitalnetworkacquisition",
      "collectionName": "blocks",
      "connection": "CosmosDBConnection"
    }
  ],
  "disabled": false
}

index.js

    module.exports = function (context, req) {
    context.log('Add block to CosmosDB.');
    if (req.body) {
        let block = req.body;
        context.bindings.block = block;
        context.res = {
            body: context.bindings.block,
            status: 201
        }
        context.done();
        return;
    }
    context.res = {
        body: undefined,
        status: 404
    };
    context.done();
   };

此代码将我的对象插入数据库,但将我的请求正文发送回客户端,这是正常的,因为以下行:

context.bindings.block = block;

这不是我想要的。我想从数据库中检索插入的对象并将其发送回客户端,以便获得创建的 ID。我不知道该怎么做。有什么建议吗?

非常感谢!

【问题讨论】:

    标签: javascript node.js azure azure-functions


    【解决方案1】:

    您可以尝试使用此代码。 创建文档时,您应该传递以下参数。

    • collLink:集合的 url = dbLink + collectionId
    • 文档定义:
    • err:错误回调
    • 文档:已创建文档

    然后你可以通过document.id获取创建的文档的id

    collLink = dbLink + '/colls/' + collectionId;
    
    function insertDocuments(collLink, callback) {
    
        client.createDocument(collLink, documentDefinition, function (err, document) {
                if (err) {
                    console.log(err);
    
                } else {
                    console.log('created ' + document.id);
    
                }
            });
    
    }   
    

    有关带有 Node.js 的 documentDb 的更多示例,您可以访问此 repo:https://github.com/Azure/azure-documentdb-node/blob/ef53e5f6707a5dc45920fb6ad54d9c7e008a6c18/samples/DocumentDB.Samples.DocumentManagement/app.js#L153-L177

    【讨论】:

    • 感谢您的回答塞巴斯蒂安。有没有办法只使用绑定来做同样的事情,而不必调用 client.createDocument (就像我的例子一样)?
    【解决方案2】:

    我知道这个问题已经得到了回答,但应该可以在调用 Azure 函数 (AF) 时设置 id 或将其添加到 AF 中。鲜为人知的事实,但 id 通常由 SDK 在客户端生成,除非提供。使用底层 REST API 时,如果没有创建文档是错误的。

    加载 DocumentDB SDK 并使用该 GUID 生成器或从开源 SDK 代码中提取代码并将其粘贴到您的 AF 中。

    getGUID = require('documentdb').Base.generateGuidId
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多