Join the Stack Overflow Community
Stack Overflow is a community of 6.9 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm trying to make a function inside an async.waterfall that checks each id in an array if there is any entry in a mongodb with this id (using Mongoose). If the id already exists it's to be removed from the array. I wrote the following function:

    function(eventIds, callback) {
        // check for duplicates
        for (var i = 0; i < eventIds.length; i++) {
            var query = Party.find({
                fbEventId: eventIds[i]
            });
            query.exec(function(err, doc) {
                if (err) return console.log(err);
                if (doc) {
                    // remove i from array
                    console.log(doc);
                }
            });
        }
        callback(null, eventIds);
    }

This however gives a warning because a new function is constructed in a for loop.

If i create the function outside the for loop like below it gives an error: ReferenceError: err is not defined.

    function(eventIds, callback) {
        // check for duplicates
        function checkDuplicate(err, doc) {
            if (err) return console.log(err);
            if (doc) {
                    // remove i from array
                console.log(doc);
            }
        }
        for (var i = 0; i < eventIds.length; i++) {
            var query = Party.find({
                fbEventId: eventIds[i]
            });
            query.exec(checkDuplicate(err, doc));
        }
        callback(null, eventIds);
    }

What would be the proper way to do this?

share|improve this question
1  
As a note, the callback will exec before all of the checkDuplicate calls execute / finish. Are you sure this is what you want? – NG. Nov 1 '13 at 12:56
    
No it's indeed not what I want, thanks for the tip :) – Bunker Nov 1 '13 at 13:35
up vote 3 down vote accepted

You are calling the function, not assigning a reference to it.

Your code

query.exec(query.exec(checkDuplicate(err, doc));

should be

query.exec(query.exec(checkDuplicate));
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.