NodeJS服务器上的Mongoose查询返回NULL

我正在查询Twitter的位置,它已成功返回。 然后这些位置被存储在一个mongodb中。 当我通过命令行查询数据库的位置:“英国”时,位置数据被返回。 但是,当我查询NodeJS服务器上的数据库,没有任何返回(空)。

这里是代码:

'use strict'; // Set default node environment to development process.env.NODE_ENV = process.env.NODE_ENV || 'development'; var express = require('express'); var mongoose = require('mongoose'); var config = require('./config/environment'); var Location = require('./api/twitter/location/twitter/location.model'); // Connect to database mongoose.connect(config.mongo.uri, config.mongo.options); mongoose.connection.on('error', function(err) { console.error('MongoDB connection error: ' + err); process.exit(-1); }); // Populate DB with sample data if(config.seedDB) { Location.remove({}, function(err) { console.log('Location collection removed'); }); } // Setup server var app = express(); var server = require('http').createServer(app); var socketio = require('socket.io')(server, { serveClient: config.env !== 'production', path: '/socket.io-client' }); require('./config/socketio')(socketio); require('./config/express')(app); require('./routes')(app); // Start server server.listen(config.port, config.ip, function () { console.log('Express server listening on %d, in %s mode', config.port, app.get('env')); }); // Expose app exports = module.exports = app; // Query Twitter for locations getLocations(); // 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); } }); // Gather available locations from Twitter function getLocations() { twitterClient.get('trends/available', {}, function(errors, locations, response) { if (!errors) { storeLocations(locations); } else { console.log(errors); } }); } // Store locations in database function storeLocations(locations) { for (var location in locations) { Location.create({ name: locations[location].name, placeType: { code: locations[location].placeType.code, name: locations[location].placeType.name }, parentId: locations[location].parentid, country: locations[location].country, woeId: locations[location].woeid, countryCode: locations[location].countryCode }, function(err) { if (err) { console.log(err); } }); } } 

任何帮助,将不胜感激,并提前感谢。

在node.js中,您对findOne的调用是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); } }); 

它看起来像你期望从callback中提供的返回值(位置)被传播到var woeId,但是这绝不会发生。

相反,您需要在callback中执行所需的任何操作,这可能与设置全局variables一样简单,但取决于您计划如何使用它。 例如:

 // 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); } }); 

但是请记住,在调用asynchronouscallback之前,该值将不可用。