1

Cursors can be easily converted to arrays using .toArray(foo) method:

var cursor = col.find({});
cursor.toArray(function (err, itemsArray) {
   /* do something */
});

But is it possible to convert itemsArray in a cursor so I will have all cursor functions?

var newCursor = foo (itemsArray);
typeof newCursor.toArray === "function" // true
4
  • Am I right that you want to emulate MongoDB cursor api? Commented Mar 25, 2014 at 12:04
  • @LeonidBeschastny If possible I don't only want to emulate but to really use an existing api for converting an array to cursor. Commented Mar 25, 2014 at 13:03
  • 1
    I doubt that such an API exists. Commented Mar 25, 2014 at 13:27
  • @LeonidBeschastny Why not just create your own iterator? It's pretty simple. See the answer. Commented Mar 27, 2014 at 14:15

1 Answer 1

2

Well it is all just JavaScript so why not create your own iterator:

var Iterator = function () {
    var items = [];
    var index = 0;

    return {

        "createCursor" : function (listing) {
            items = listing;
        },

        "next" : function () {
            if ( this.hasNext() ) {
                return items[index++];
            } else {
                return null;
            }
         },

         "hasNext" : function () {
             if ( index < items.length ) {
                 return true;
             } else {
                 return false;
             }
         }
     }
}();

So then you use it like this with an array:

var cursor = new Iterator();
cursor.createCursor( array );

cursor.next();    // returns just the first element of the array

So just a general way to write an iterator. If you want more functionality then just add the other methods to the prototype.

Sign up to request clarification or add additional context in comments.

5 Comments

@IonicăBizău You basically just changed a "cursor" into an "array". So there is no "API" available. Writing an iterator is quite trivial in any language, as has been shown.
You're correct. I waited the official answer from Mongo devs, and this is: jira.mongodb.org/browse/NODE-164
Can you please make it possible to pipe such an array to response? cursor.pipe(res)
@IonicãBizãu The node driver supports conversion to the stream interface out of the box. If you wanted to implement your own streaming iterator you can follow the streaming interface guide
How to reopen request of jira.mongodb.org/browse/NODE-164 ? It is not a driver responsability, it is a orthogonal semantic complement of a language constructor... Mongo framework, nowadays, is like a language...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.