First of all, you'd need to install the documentdb module via npm. Use the following command:
npm install documentdb --save
After that, you've finished setting up. Now you can start writing some code to query the collection in the database. The following is an example of querying a family collection with Azure HTTP-trigger function.
The folder structure:
- node_modules/
- .gitignore
- config.js
- function.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);
}
});
});
};
Tested result:
For more details, please refer to https://docs.microsoft.com/en-us/azure/documentdb/documentdb-nodejs-get-started.