CouchDB- basic grouping question - couchdb

I have a user document which has a group field. This field is an array of group ids. I would like to write a view that returns (groupid as key) -> (array of user docs as val). This mapping operation seems like a good beginning.
function(doc)
{
var type = doc.type;
var groups = doc.groups;
if(type == "user" && groups.length > 0)
{
for(var i = 0; i < groups.length; i++)
{
emit(groups[i], doc);
}
}
}
But there's obviously something very wrong with my attempt at a reduce:
function(key, values, rereduce)
{
var set = [];
var seen = [];
for(var i = 0; i < values.length; i++)
{
var _id = values[i]._id;
if(seen.indexOf(_id) == -1)
{
seen.push(_id);
set.push(values[i]);
}
}
return set;
}
I'm running CouchDB 0.10dev. Any help appreciated.

The answer to this after checking on the CouchDB IRC is that you don't need reduce for this at all. Just provide a key=groupId, something like the following:
http://localhost:5984/somedb/_design/bygroup/_view/all?key=2

Related

Calculate the sum of a specific array data

After calling all the data from my database, I would like to try and calculate the individual values of my array. I have made 2 users state as "banned"
//get all banned status for all users
res.data.data.forEach((dataItem, index) => {
console.log(`Banned ${index}`, dataItem.banned);
I would like to try and get the sum of "banned" and "not banned" which in this case is "banned 2" and "NotBanned 2"
tried this but dint work
for (const dataItem of res.data.data) {
let NotBanned = 0;
if(dataItem.banned === false){
NotBanned++;
console.log("Not Banned", NotBanned);
}
}
for (const dataItem of res.data.data) {
var BannedUsers = 0;
if(dataItem.banned === true){
BannedUsers++;
console.log("Not Banned",BannedUsers);
}
}
let
bannedUsers = 0,
unBannedUsers = 0;
const response = res.data.data
for(let users = 0; users < response.length; users ++ ) {
if(!response.banned) {
unBannedUsers += users;
}
else {
bannedUsers += users;
}
}
console.log(`Banned Users : ${bannedUsers} , UnBanned Users : ${unBannedUsers}` )

How to verify a document from QLDB in Node.js?

I'm trying to verify a document from QLDB using nodejs. I have been following the Java verification example as much as I can, but I'm unable to calculate the same digest as stored on the ledger.
This is the code I have come up with. I query the proof and block hash from QLDB and then try to calculate digest in the same way as in Java example. But after concatinating the two hashes and calculating the new hash from the result I get the wrong output from crypto.createHash('sha256').update(c).digest("base64"). I have also tried using "base64" instead of "hex" with different, but also wrong result.
const rBlock = makeReader(res.Revision.IonText);
var block = [];
rBlock.next();
rBlock.stepIn();
rBlock.next();
while (rBlock.next() != null) {
if (rBlock.fieldName() == 'hash') {
block.push(Buffer.from(rBlock.byteValue()).toString('hex'));
}
}
console.log(block);
var proof = [];
const rProof = makeReader(res.Proof.IonText);
rProof.next();
rProof.stepIn();
while (rProof.next() != null) {
proof.push(Buffer.from(rProof.byteValue()).toString('hex'));
}
var ph = block[0];
var c;
for (var i = 0; i < proof.length; i++) {
console.log(proof[i])
for (var j = 0; j < ph.length; j++) {
if (parseInt(ph[j]) > parseInt(proof[i][j])){
c = ph + proof[i];
break;
}
if (parseInt(ph[j]) < parseInt(proof[i][j])){
c = proof[i] + ph;
break;
}
}
ph = crypto.createHash('sha256').update(c).digest("hex");
console.log(ph);
console.log();
}
I have figure it out. The problem was that I was converting the blobs to hex strings and hash them instead of the raw values. For anyone wanting to verify data in node, here is the bare solution:
ledgerInfo.getRevision(params).then(res => {
console.log(res);
const rBlock = makeReader(res.Revision.IonText);
var ph;
rBlock.next();
rBlock.stepIn();
rBlock.next();
while (rBlock.next() != null) {
if (rBlock.fieldName() == 'hash') {
ph = rBlock.byteValue()
}
}
var proof = [];
const rProof = makeReader(res.Proof.IonText);
rProof.next();
rProof.stepIn();
while (rProof.next() != null) {
proof.push(rProof.byteValue());
}
for (var i = 0; i < proof.length; i++) {
var c;
if (hashComparator(ph, proof[i]) < 0) {
c = concatTypedArrays(ph, proof[i]);
}
else {
c = concatTypedArrays(proof[i], ph);
}
var buff = crypto.createHash('sha256').update(c).digest("hex");
ph = Uint8Array.from(Buffer.from(buff, 'hex'));
}
console.log(Buffer.from(ph).toString('base64'));
}).catch(err => {
console.log(err, err.stack)
});
function concatTypedArrays(a, b) {
var c = new (a.constructor)(a.length + b.length);
c.set(a, 0);
c.set(b, a.length);
return c;
}
function hashComparator(h1, h2) {
for (var i = h1.length - 1; i >= 0; i--) {
var diff = (h1[i]<<24>>24) - (h2[i]<<24>>24);
if (diff != 0)
return diff;
}
return 0;
}

Recursively get documents in Azure Cosmos Stored Procedure

I'm trying to generate a content tree for a simple wiki. Each page has a Children property that stores the id of other wiki pages. I'm trying to write a SPROC that gets all of the documents, then iterate over each page's Children property and replace each item with an actual wiki page document. I'm able to get the first set of documents, but the wikiChildQuery returns undefined and I'm not quite sure why.
I've been able to get a document with the query alone but for some reason, it doesn't work within the SPROC. Is there something I'm missing here?
function GetWikiMetadata(prefix) {
var context = getContext();
var collection = context.getCollection();
var metadataQuery = 'SELECT {\"ExternalId\": p.ExternalId, \"Title\": p.Title, \"Slug\": p.Slug, \"Children\": p.Children} FROM Pages p'
var metadata = collection.queryDocuments(collection.getSelfLink(), metadataQuery, {}, function (err, documents, options) {
if (err) throw new Error('Error: ', + err.message);
if (!documents || !documents.length) {
throw new Error('Unable to find any documents');
} else {
var response = getContext().getResponse();
for (var i = 0; i < documents.length; i++) {
var children = documents[i]['$1'].Children;
if (children.length) {
for (var j = 0; j < children.length; j++) {
var child = children[j];
children[j] = GetWikiChildren(child);
}
}
}
response.setBody(documents);
}
});
if (!metadata) throw new Error('Unable to get metadata from the server');
function GetWikiChildren(child) {
var wikiChildQuery = metadataQuery + ' WHERE p.ExternalId = \"' + child + '\"';
var wikiChild = collection.queryDocuments(collection.getSelfLink(), wikiChildQuery, {}, function(err, document, options) {
if (err) throw new Error('Error: ', + err.message);
if (!document) {
throw new Error('Unable to find child Wiki');
} else {
var children = document.Children;
if (children) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
children[k] = GetWikiChildren(child);
}
} else {
return document;
}
}
if (!wikChild) throw new Error('Unable to get child Wiki details');
});
}
}
1.I'm able to get the first set of documents, but the wikiChildQuery
returns undefined and I'm not quite sure why.
Firstly, here should be corrected. In the first loop, you get children array with documents[i]['$1'].Children, however , in the GetWikiChildren function you want to get children array with document.Children? Surely,it is undefined. You need to use var children = document[0]['$1'].Children;
2.It seems that you missed the replaceDocument method.
You could refer to the snippet code of your metaDataQuery function:
for (var i = 0; i < documents.length; i++) {
var children = documents[i]['$1'].Children;
if (children.length) {
for (var j = 0; j < children.length; j++) {
var child = children[j];
children[j] = GetWikiChildren(child);
}
}
documents[i]['$1'].Children = children;
collection.replaceDocument(doc._self,doc,function(err) {
if (err) throw err;
});
}
3.Partial update is not supported by Cosmos db SQL Api so far but it is hitting the road.
So, if your sql doesn't cover your whole columns,it can't be done for your replace purpose.(feedback) It is important to note that the columns which is not mentioned in the replace object would be devoured while using replaceDocument method.

Loop is not working in node.js

Here is my code :
for (var j in albums){
var album_images = albums[j].images
var l = album_images.length
for ( var i = 0; i < l; i++ ) {
var image = album_images[i]
Like.findOne({imageID : image._id, userIDs:user._id}, function(err,like){
if(like){
console.log(i)
//console.log(albums[j].images[i])
//albums[j].images[0].userLike = true;
}
})
}
}
Here I have albums, and I am populating images of album
So album variable contains all the albums and inside them their images will also be there in a array
I want to add a extra field (userLike) in each images.
Problem here is all the time the value of the i is 3 (that is the number of images in a album (album_images.length) - for the time being I have only one album)
I think the problem could be because the callback of Like.findOne calls only when all the loops has finished executing (just a guess).
How can I make it work so that I will get all the loop values in console.log(i) ?
Thanks in advance
I prefer using forEach:
albums.forEach(function(album, j) {
var album_images = album.images;
album_images.forEach(function(image, i) {
Like.findOne(...);
});
});
Just a tip: instead of performing a findOne for each image, you may consider using $in.
Alternatively you could define a function in order to have a scope where the variable doesn't change.
...
handle_album_image = function(image, i, j) {
Like.findOne({imageID : image._id, userIDs:user._id}, function(err, like){
if(like){
console.log(i)
//console.log(albums[j].images[i])
//albums[j].images[0].userLike = true;
}
})
}
for ( var i = 0; i < l; i++ ) {
var image = album_images[i]
handle_album_image(image, i, j)
}

Search not working on item record

I am not able to get the list of item.I am using a saved search and want to create a list of all the item record id from it.
But it is not working.
my code
var loadSearch=nlapiLoadSearch('item','customsearch12');
var getData = loadSearch.runSearch();
var itemCol=new Array();
for(var i=0;i<getData.length;i++)
{
itemCol.push(getData[i].getId());
}
Can somebody help me with this
try this code
var loadSearch=nlapiLoadSearch('item','customsearch12');
var getData = loadSearch.runSearch();
var itemCol=new Array();
getData.forEachResult(function (searchRow) {
itemCol.push(searchRow.getId());
return true;
});
when you use a nlapiLoadSearch, the result is nlobjSearchResultSet and not an array like in the case of nlapiSearchRecord.
if you use nlapiSearchRecord, then you can loop through the result like you were trying in your code, i.e. using index
The answer given above by Nitish is perfectly correct but you need to consider one more thing.
nlapiLoadSearch api returns 4000 records at a time.
The nlapiSearchRecord api returns only 1000 records at a time , so what if your saved search consists of more than 1000 records.
So you will miss those extra items.
so here is the code to have better results
//Searching the items
var searchResults = nlapiSearchRecord('item', 'customsearch12',null,null);
var searchedItemId;
var lastId;
var completeResults = new Array();
var arrNewFilters=[];
if (searchResults != null) {
completeResults = completeResults.concat(searchResults);
}
else {
completeResults = null;
nlapiLogExecution('Debug', 'No item found',
weight + ' Null result');
}
if (completeResults != null) {
if (searchResults.length == 1000) {
while (searchResults.length == 1000) {
//Initialize variable
lastId = "";
//Get Record Id of Last record,
//to search the item record again from that record
lastId = searchResults[999].getId();
//start after the last id searched
arrNewFilters.push(new nlobjSearchFilter("internalidnumber",
null, "greaterthan", lastId));
//Lets search again
var searchResults = nlapiSearchRecord('item', 'customsearch12',
arrNewFilters, null);
if (searchResults != null) {
//Append the search result to the result present before
completeResults = completeResults.concat(searchResults);
}
}
}
for (var result = 0; result < completeResults.length; result++) {
//Loop through the items
}
Hope you got me Nitish!!!
Here's a sample of how to fetch over 1k of results in NetSuite/NetScript.
The search "customsearch_tel_tg_by_trunk_type" is not really relevant.
Complete sample of 1k+ results fetch in NetSuite/NetScript
You could get all the results one by one using a callback function till all the records are iterated.
var search = nlapiLoadSearch('item','customsearch12');
var resultSet = loadSearch.runSearch();
var itemCol=new Array();
resultSet.forEachResult(function (iterator) {
itemCol.push(iterator.getId());
return true;
});
or you could load few records of it using the getResults of the nlobjResultSet
var search = nlapiLoadSearch('item', 'customsearch12');
var resultSet = search.runSearch();
var results = resultSet.getResults(0, 100);//get the results from 0 to 100 search results
var itemCol = new Array();
for(var i in results)
{
itemCol.push(results[i].getValue('id'));
}

Resources