javascriptmarklogicsjs

Implement For Loop in Marklogic Javascript?


I can get all the URIs of the documents in a collection by using below XQuery:

for $doc in fn:collection("transform") 
return xdmp:node-uri($doc)

But, when I tried to implement this in a Javascript module in MarkLogic, it is getting only last document in the database collection.

'use strict';
declareUpdate()
var docs = fn.collection("transform");
for(var doc of docs) {
  xdmp.nodeUri(doc)
}

It is not giving all the URIs in the collection, but rather it's only returning the last URI of the document.

How can I get it to return all of the URIs?


Solution

  • Create an array and add each of the URIs to that array in your for loop, then either return the array:

    'use strict';
    declareUpdate()
    var docs = fn.collection("transform");
    var results = [];
    for (var doc of docs) {
     results.push(xdmp.nodeUri(doc));
    }
    results;
    

    or return a Sequence using Sequence.from():

    'use strict';
    declareUpdate()
    var docs = fn.collection("transform");
    var results = [];
    for (var doc of docs) {
     results.push(xdmp.nodeUri(doc));
    }
    Sequence.from(results);
    

    However, if you simply want to return the URIs, then it would be better/easier to use cts.uris() with a cts.collectionQuery():

    'use strict';
    declareUpdate();
    cts.uris("", null, cts.collectionQuery("transform"));