0

I am new in node js and mongoose. I am trying to retrieve user from executed mongoose query on answer on: stack-overflow-answer

Here is my controller code (it contains both: callback and promises approach)

exports.getUser = (req, res, next) => {

    var searchQuery = {...};
    var result = [];
    User.find(searchQuery, function (err, found) {
            console.log(" >>>> inside", found)
            result = found;
        }
    )

    console.log(" >>>> outside ", result)

    var result2 = [];
    User.find(searchQuery)
        .exec()
        .then(function(found){
            console.log(" >>>> inside", found)
            result2 = found
            return found
        }
    )

    console.log(" >>>> outside ", result2)

    res.status(200).json(result)
}

In both cases in console it is printing query result inside callback and outside it remains empty, why?

Thanks for help :)

Atishay Jain
  • 1,425
  • 12
  • 22
Wicia
  • 575
  • 3
  • 9
  • 28
  • Your code outside of the function is reached before the callback is even executed. Simple asynchronous behaviour. –  Oct 19 '18 at 11:07

2 Answers2

1

If your environment supports async/await, you can also do this:

exports.getUser = async (req, res, next) => {
    const searchQuery = {...}
    const result = await User.find(searchQuery)
    res.status(200).json(result)
}
mtkopone
  • 5,955
  • 2
  • 27
  • 30
0

I can't really understand what you are trying to do, but your code should look something like:

exports.getUser = (req, res, next) => {

    // 1: first query

    var searchQuery = {...};

    User.find(searchQuery, function (err, foundX) {

        // 2: second query

        var searchQuery = {...};

        User.find(searchQuery, function (err, foundY) {

            // 3: send response

            res.status(200).json(foundY);

        });

    });

}

You need to wait for the asynchronous code to be executed.

  • I wanted to implement such scenario: find X object in db, get from it list of ids referencing to Y objects and finally return list containing X object with Y object list (e.g details). – Wicia Oct 19 '18 at 11:20
  • Yeah, that was my initial idea :) Is it possible to achieve it without nesting? – Wicia Oct 19 '18 at 12:55
  • 1
    You could use async / await as proposed by @mtkopone –  Oct 19 '18 at 12:58