0

Following is my code:

Middleware:

app.get('/myapp', function (req, res) {
    db.collection('mydocument').find(function (err, docs) {

        var result = checkAuthorisedUser(); //calling function checkAuthorisedUser from here

        console.log("result:" + result);
        if (docs.length > 0)
            res.json(docs);
        else
            res.json(null);
    });
});

Function checkAuthorisedUser()

function checkAuthorisedUser() {
    var result;
    db.collection('user').find({uid: session.uid}, function (err, docs) {        
        console.log(docs); // Here its displaying result
        result = docs;
    });    
    return result;
}

In above code I'm trying to call a function from middleware where I've written mongodb query to find userid but its not assigning docs to var result so that's why it's not returning the data and showing undefined in the console.log(result).

I'm beginner in express.js. Any help would be appreciated.

J.K.A.
  • 7,272
  • 25
  • 94
  • 163
  • Your `console.log(result)` is logging an as-yet-unused variable which is why it's undefined. I presume you meant to log `docs`? –  Apr 11 '16 at 10:20
  • @JohnO'Mahoney: Sorry that was typo. Modified post. – J.K.A. Apr 11 '16 at 10:23
  • @chridam: I don't think its duplicate bcz the solution I want is in `express.js` not in js, ajax or jquery – J.K.A. Apr 11 '16 at 10:42
  • 1
    Regardless of the question tags, the fundamentals encapsulated in the answers still remain; you are trying to return a result from an asynchronous function, you need to use a callback for this. – chridam Apr 11 '16 at 11:26
  • @chridam: okay I've tried callback function `var checkAuthorisedUser = function () { db.collection('user').find({dtid: session.dtid}, function (err, docs) { return docs; }); };` but still but still same issue – J.K.A. Apr 11 '16 at 12:43

0 Answers0