Reputation: 1
I am using node.js and ibm bluemix to run the back-end apps. I am using cloudant module. But in github as I search, I only found how to make a query with 1 result. So I want to ask you guys how can I make a query with multiple results. I want to make it in my app.js. My sample database are
{
"userid":"chris"
"time":"12.20",
"power":"200",
}
{
"userid":"chris"
"time":"12.30",
"power":"250",
}
And there will be plenty of data with same userid and different time and power. How do I want to make the query it and publish it with mqtt?
Thanks for your help.
Upvotes: 0
Views: 762
Reputation: 1010
You probably want to create a view for your cloudant database and then query the view. This will use the map and possibly the reduce features in the view. So, for example, if you wanted to find all records related to a single userid, you might create a view like the following:
{
"_id": "_design/views",
"views": {
"byUser": {
"map": "function (doc) { if (doc.userid) {emit(doc.userid, doc); } }"
}
}
}
This is a slightly lazy way to handle the mapping process as it creates a view with all of your document contents in the view. That way, when the query results are returned, the result set includes complete records, rather than just an _id and the userid fields. This reduces the transactional load on the cloudant db, but increases the size of the actual db.
Upvotes: 0
Reputation: 240
get the sample nodejs and cloudant here :
git clone https://github.com/IBM-Bluemix/get-started-node
you will find a loop on the cloudant db result object :
mydb.list({ include_docs: true }, function(err, body) {
if (!err) {
body.rows.forEach(function(row) {
if(row.doc.name)
names.push(row.doc.name);
});
response.json(names);
}
});
});
next in the watson iot platform service i have found a client library for nodejs. Samples here
i think it's easier (for me) to start with the node-red starter boilerplate app.
to store your 3 elements in the doc :
mydb.insert({ "userid" : "chris","time":"12:20","power":"200" }, function(err, body, header) {
if (err) {
return console.log('[mydb.insert] ', err.message);
}
response.send("added to the database.");
});
to get them :
mydb.list({ include_docs: true }, function(err, body) {
if (!err) {
body.rows.forEach(function(row) {
if(row.doc.userid)
response.send(row.doc.userid+" "+row.doc.power+" "+row.doc.time);
});
}
});
Upvotes: 2