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

时间:2015-08-04 18:55:25

标签: node.js mongodb mongoose

我在Twitter上查询已成功返回的位置。然后将这些位置存储在mongodb中。当我通过命令行查询数据库的位置时:'英国',返回位置数据。但是,当我在NodeJS服务器上查询数据库时,没有返回任何内容(null)。

以下是代码:

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

对此的任何帮助都将非常感谢并提前感谢。

1 个答案:

答案 0 :(得分:1)

在node.js中,对findOne的调用是异步的。

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

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

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

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

但请记住,在调用异步回调之前,该值将不可用。