LittleBigFrog
LittleBigFrog

Reputation: 95

Nodejs assign var once mongodb query finished (callback misunderstanding needing a simple example)

I'm calling a mongodb query and need to assign the result to a value.

   function oneref(db, coll, cb) {
    var pipeline = [{ "$sample": { size: 1 } }]
    var ohoh
    coll.aggregate(pipeline, function (err,oneref) {
        ohoh=oneref[0].code
    })
    console.log('hoho?: ' + ohoh)
    cb(null, db, coll)   
},

I understand I have an issue understanding callback, but even checking all hello world examples, I'm struggling.

How to write it in the simplest way so I only assigne the var hoho when the query finished?

Thanks a lot in advance.

Upvotes: 0

Views: 53

Answers (1)

chridam
chridam

Reputation: 103365

You're getting undefined value for the variable hoho is because the aggregate() cursor method is asynchronous, and can finish at any time. In your case, it is finishing after you're using console.log(), so the values are undefined when you're accessing them.

Asign the variable as the argument to the callback within the aggregate() function callback i.e.

function oneref(db, coll, cb) {
    var pipeline = [{ "$sample": { size: 1 } }];
    coll.aggregate(pipeline, function (err, oneref) {
        if (err) return cb(err);
        var hoho = oneref[0].code
        console.log('hoho?: ' + hoho);
        cb(null, hoho);   
    });    
};

Calling the oneref function:

oneref(db, collection, function(err, result){
    console.log(result); // logs the oneref[0].code
});

Refer to this Question for a better understanding on how callback functions work.

Upvotes: 1

Related Questions