EnterpriseXL
EnterpriseXL

Reputation: 477

Iterating on Cursor from MongoDB

I am trying to get all the documents in the collection, so I can do something based on them.

I am using the following code:

var test = pool.getDbCollection('Events');
test.find()   //get them all
    .each(function (error, doc) {
        if (error) {
            throw error;
        } else {
                    //I am not getting here
                    //I am getting TypeError: Object 5 has no method 'each'
                    //And there are 5 Documents in the collection
        }
    });
}

And keep getting: Object 5 has no method 'each'

This function works just fine (same connection properties):

 exports.getEventData = function (data) {
    var deferred = Q.defer();
    var eventCollection = pool.getDbCollection('Events');//TO DO Move this to config file
    eventCollection.findOne({"id":data},
        function (err, docs) {
            if (!err) {
                deferred.resolve(docs);
                console.log('INFO(getEvents Method): Got the data !!!!')

            } else {
                deferred.reject('INFO(getEvents Method): Failed to get the data');
            }
        }
    );

    return deferred.promise;
};

It looks like each function is tried on the last object, but that last object is not in existance. at least it look to me that way. But I might be totally wrong.

Upvotes: 0

Views: 188

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59763

doc will be null in the last iteration of the loop as a signal that the loop has completed.

Upvotes: 1

Related Questions