javascript - 如何使用Azure函数返回documentDB文档?

标签 javascript node.js azure azure-cosmosdb azure-functions

我创建了一个azure函数以及一个带有用户集合的documentDB数据库,但是,我坚持将它们两个相互连接。我只想发送一个用户名,该函数查询数据库,然后返回具有该唯一用户名的用户。

我正在使用 Node js。有什么想法吗?

谢谢

最佳答案

首先,您需要通过 npm 安装 documentdb 模块。使用以下命令:

npm install documentdb --save

之后,您就完成了设置。现在您可以开始编写一些代码来查询数据库中的集合。以下是使用 Azure HTTP 触发函数查询family集合的示例。

文件夹结构:

  • Node 模块/
  • .gitignore
  • config.js
  • 函数.json
  • index.js
  • package.json

CONFIG.JS

var config = {}

config.endpoint = "https://<documentdb name>.documents.azure.com:443/";
config.primaryKey = "<primary key>";

config.database = {
    "id": "FamilyDB"
};

config.collection = {
    "id": "FamilyColl"
};

module.exports = config;

INDEX.JS

var documentClient = require("documentdb").DocumentClient;
var config = require("./config");

var databaseUrl = `dbs/${config.database.id}`;
var collectionUrl = `${databaseUrl}/colls/${config.collection.id}`;

var client = new documentClient(config.endpoint, { "masterKey": config.primaryKey });

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

    if (req.query.name || (req.body && req.body.name)) {

        var name = req.query.name || req.body.name;

        queryCollectionByName(name).then((result) => {
            context.log('result: ', result);
            res = {
                body: "Result: " + JSON.stringify(result)
            };

            context.done(null, res);

        }, (err) => {
            context.log('error: ', err);
            res = {
                body: "Error: " + JSON.stringify(err)
            };

            context.done(null, res);
        });

    }
    else {
        res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };

        context.done(null, res);
    }
};


function queryCollectionByName(name) {

    return new Promise((resolve, reject) => {
        client.queryDocuments(
            collectionUrl,
            `SELECT VALUE r.children FROM root r WHERE r.lastName = "${name}"`
        ).toArray((err, results) => {
            if (err) reject(err)
            else {
                resolve(results);
            }
        });
    });
};

测试结果:

enter image description here

更多详情请引用https://learn.microsoft.com/en-us/azure/documentdb/documentdb-nodejs-get-started .

关于javascript - 如何使用Azure函数返回documentDB文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993999/

相关文章:

node.js - Sequelize 获取关联表数据

node.js - 在 nodejs 中重用 postgresql 连接池

node.js - 从 Express 服务器以编程方式构建 Nuxt.js 时出错

python - 在azure上部署python Azure函数时出现“找不到模块”错误

azure - 在 Azure 服务总线订阅上配置共享访问签名

javascript - AngularJS 中的 $scope 值

javascript - 如何在 React Native/Expo 中请求权限?

javascript - 单击嵌套的 Bootstrap Dropdown <li> 时防止滚动

javascript - 是否可以检测单击 Canvas 的位置并在单击后删除项目?

azure - Azure 应用服务插槽上是否可以自定义错误页面?