我创建了一个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);
}
});
});
};
测试结果:
更多详情请引用https://learn.microsoft.com/en-us/azure/documentdb/documentdb-nodejs-get-started .
关于javascript - 如何使用Azure函数返回documentDB文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993999/