Mongoose query on NodeJS server returns NULL Mongoose query on NodeJS server returns NULL mongoose mongoose

Mongoose query on NodeJS server returns NULL


In node.js your call to findOne is asynchronous.

// Find location 'United Kingdom'var woeId = Location.findOne({'name': 'United Kingdom'}, 'woeId', function (err, location) {    console.log(location);    if (!err) {        return location;    } else {        console.log(err);    }});

It looks like you expect the return value (location) that you provide from the callback to be propogated out to var woeId, but that will never happen.

Instead you need to perform whatever action is needed from within the callback, which could be as simple as setting a global variable, but depends on how you plan on using it. For example:

// Find location 'United Kingdom'var woeId;Location.findOne({'name': 'United Kingdom'}, 'woeId', function (err, location) {        console.log(location);        if (!err) {                woeId = location;        } else {                console.log(err);        }});

But just remember that the value won't be available until the asynchronous callback is invoked.