node.js - NodeJS 服务器上的 Mongoose 查询返回 NULL

标签 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);
            }
        });
    }
}

对此的任何帮助将不胜感激,并提前致谢。

最佳答案

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

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

关于node.js - NodeJS 服务器上的 Mongoose 查询返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31817075/

相关文章:

node.js - 按 id 过滤 KeystoneJS 关系

未添加 Javascript 对象属性

node.js - 如何使用expressJS使用新数据重新渲染 View ?

node.js - Neo4j 将数据序列化为 JSON

javascript - 同步函数在异步函数中的影响

mysql - 统一使用 MongoDB 和 MySQL

python - 如何处理 MongoDB (pyMongo) 中的 DuplicateKeyError?

mysql - 服务器 Ajax/http 上的 Nodejs 调用不读取新数据 Mongodb

node.js - res.send,之后如何退出?

python - pymongo (python+mongodb) 删除集合/gridfs?