0
votes

I created an azure function as well as a documentDB database with a users collection, however, I am stuck at connecting the two of them to each other. I want to just send a username and the function queries the database then returns the user with that unique username.

I am using node js. Any ideas?

Thanks

1
Could you provide an example code that you have tried and so we can potentially help? BTW, a good reference for DocumentDB and Azure Functions binding is Azure Functions DocumentDB bindings.Denny Lee

1 Answers

2
votes

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:

enter image description here

For more details, please refer to https://docs.microsoft.com/en-us/azure/documentdb/documentdb-nodejs-get-started.