1

I'm fixing some bugs in one project. I need synchronous cursor, to load data in loop. I have code:

var mongo     = require('mongojs'),
    dataMaps  = [];

mongo.penguin_friends.find({ user_id_1: id_user }, function(err, friends) {     
    friends.forEach(function(data) {
        var cursor = mongo.penguin_user_maps3.find({ user_id: data.id_user }, { fields: { maps: 1 } });
    //I need to do dataMaps.push(cursor.data);

    });

    console.log("processingThisSomething()");

    processSomething();     
}); 

I need to complete this request before calling processSomething(); So I need to process mongodb query inside a loop synchronously.

2
  • 2
    It's not possible to make the queries synchronous. The API doesn't support it. But, you can use an iterator that supports asynchronous blocks. E.g., async.each(). Commented May 8, 2014 at 15:02
  • Could you please give an example in aswer? Commented May 8, 2014 at 15:16

1 Answer 1

4

It's not possible to make the queries synchronous as the API doesn't support it.

You'll have to provide a callback to .find() or a cursor method to receive the results:

cursor.toArray(function (err, maps) {
    if (!err) {
        dataMaps.push(maps);
    }
});

But, you can replace the iterator with one that's asynchronous-aware, such as async.each(), to continue when they've completed:

async.each(
    friends,

    function (data, callback) {
        var cursor = mongo....;

        cursor.toArray(function (err, maps) {
            if (!err) {
                dataMaps.push(maps);
            }

            callback(err);
        });
    },

    function (err) {
        if (!err) {
            processSomething();
        }
    }
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.