0

I am trying to call a function that retrives all the document from a collection and returns the data. Now, everything works fine but for some reason , I am getting an undefined response from my function callback. What could I be doing wrong?

var findImages = function(db, callback) {
    var s ="";
    db.collection('imageinfo', function(err, collection) {
        collection.find().toArray(function(err, items) {

            for(var i=0;i<items.length;i++){
                console.log("imagename",items[i].imagename);
                s =s + items[i].imagename+",";

            }

            if(i==items.length){
                callback(s);

            }
        });


    });



};


app.get("/fetchrecords",function(req,res){
    console.log("entered");
    findImages(db,function(req,res){
     console.log("res",res);
    });

    res.end("Sent records");

});
1
  • ... function(err, items) { if (err) return callback(err) .... Commented Oct 19, 2017 at 9:52

2 Answers 2

1

I am getting an undefined response from my function callback.

Callback of findImages only returns one parameter when invoked callback(s);

But in your callback definition you logging second argument. Instead, log only first argument

findImages(db,function(res){
 console.log("res",res);
});
Sign up to request clarification or add additional context in comments.

Comments

0

i will never be the same as items.length. Because reason 1 i is not in your for loop, so it is out of scope. Reason 2, even if i is in your loop, your loop will give i a maximum value of items.length -1 because you use <.

Your solution:

var findImages = function(db, callback) {
    var s ="";
    db.collection('imageinfo', function(err, collection) {
        collection.find().toArray(function(err, items) {
           var i = 0;
            while( i<items.length){
                console.log("imagename",items[i].imagename);
                s =s + items[i].imagename+",";
                i++;
            }
              callback(s);

        });


    });



};

Comments

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.