Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute callback for each document found when mongoose executes find()

I have:

Emotion.find (query, "-_id", opts, function (error, e){
    if (error) return cb (error, 500);
    for (var i=0, len=e.length; i<len; i++){
        e[i] = convert (e[i]);
    }
    cb (null, e);
});

If the function returns 1k documents I have to iterate 1k times.

How can I add a callback that is executed for every document? Something like:

var each = function (e){
    return convert (e);
};

Emotion.find (query, "-_id", opts, each, function (error, e){
    if (error) return cb (error, 500);
    cb (null, e);
});

I basically need to use each() from mongodb: http://mongodb.github.com/node-mongodb-native/api-generated/cursor.html#each


Edit: Perhaps this can be done listening a data event from a stream and pushing the document to an array:

http://mongoosejs.com/docs/api.html#query_Query-stream

like image 408
Gabriel Llamas Avatar asked Apr 23 '26 10:04

Gabriel Llamas


1 Answers

As I said, with streams:

var emotions = [];

Emotion.find (query, "-_id", opts).stream ()
        .on ("error", function (error){
            cb (error, 500);
        })
        .on ("data", function (doc){
            emotions.push (convert (doc));
        })
        .on ("close", function (){
            cb (null, emotions)
        });

Edit: The above solution is much slower than this:

var emotions = [];

//Get the collection... then:

collection.find (query, opts, function (error, cursor){
    if (error) return cb (error, 500);

    cursor.each (function (error, doc){
        if (error) return cb (error, 500);
        if (!doc) return cb (null, emotions);
        emotions.push (convert (doc));
    });
});
like image 115
Gabriel Llamas Avatar answered Apr 24 '26 23:04

Gabriel Llamas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!