Search code examples
jsonmarklogicserverside-javascript

How to return a collection of JSON documents as a JSON array


I have a collection of JSON documents in MarklLogic which I want to return to an API call as a JSON Array.

fn.collection('my-users')

Returns a sequence of JSON docs, I need a valid JSON object, an array. I am doing this in serverside java script, pushing to a new empty array().

No real example documentation to my knowledge, only in XQuery some examples.Google keeps referring to this very high level documentation here

var myArray = [];

for (d of fn.collection('my-users')){
  myArray.push(d);
}

myArray

Do I need to loop over each item in the sequence to push to an array or is there a more elegant/quicker solution?

hugo


Solution

  • Iterables are from ES6 and are (from what I understand), one of the only things carried over for the initial release of SJS along with sub-sequences.

    The reason for these is so that you get the same behaviour as you would get with sequences and sub-sequences in xQuery. (different notation in the two languages, but identical behaviour)

    If there were a full implementation of ES6, then the answer for you would be Array.from(iteratable)

    However, without that feature, then I think you are using the most efficient way. But be careful that you don't suck your entire database into memory with the pushing from iterator to array.

    I am curious of your use-case for needing them in an array actually..

    -David