Search This Blog

Saturday 19 March 2016

connecting to documentdb from nodejs using bluemix/azure

Problem Statement:
I want to connect to documentdb using nodejs run time. i will be receiving a POST request and i have to add time stamp to it and store it in azure's document db.

we need to include a couple of npm packages to get it.
Solution:
--save is important as we need to upload it to azure for hosting. sometimes those npm packages installtion may fail in cloud.

npm install express --save //for expressJS, which exposes services
npm install cfenv --save //for bluemix hosting, if you are hosting in some other cloud it can be ignored
npm install body-parser --save //for reading the received request
npm install documentdb --save //for documentdb functions.
npm install async --save //for making request
npm install moment --save //for dealing with time stamps

then, need to make connections and run queries, here is the code for it.
https://github.com/Azure/azure-documentdb-node use this link to see some samples. first lets see how to list all documents in my collection using queries.

1. Create client
2. create your required query.
3. queryDocuments

var client = new DocumentClient(host, {masterKey: mymasterkey});
//masterKey can be found in your azure document db.
var querySpec = {query: 'SELECT * FROM CTransactions c order by c.TimeStamp desc'};
//i am listing all transactions from my collection in descending order
client.queryDocuments(collLinkTransactions, querySpec).toArray(function (err, results) {
if(err){
handleError(err);
}
else if(results.length==0){
res.end("Not Started");
}
else {
                      //use the data as you want
                 }
});

collLinkTransactions is the url link to my documentdb collection.
i am returning the query result in an array and if no errors and length is>0 i will process it and send to my client.

here is the complete code:
run it using> node app.js
complete can be found here

No comments:

Post a Comment