Nodejs在从mongodb检索数据之前发送空响应

nodejs sends empty response before data retrieved from mongodb

本文关键字:响应 在从 mongodb 检索 数据 Nodejs      更新时间:2023-09-26

当我使用jQuery ajax从nodejs(与express4)检索数据时,nodejs发送空响应之前从mongodb加载数据。

来自nodejs控制台的消息:

GET /query?uid=1 - - ms - -

这是来自Chrome控制台的错误信息:

GET http://192.168.1.105:3000/query?uid=1 net::ERR_EMPTY_RESPONSE

我可以确认数据正确地从mongodb加载,因为数据可以在nodejs发送空响应后在nodejs控制台打印。这就是问题所在。为什么nodejs在数据准备好之前向客户端发送响应?

我知道nodejs是异步的,我很注意这个伟大的功能,但我仍然有这个问题。

这是我的客户代码:

$.getJSON('/query', {uid:1}, function(response) { console.log('finished!'); });
这是我的服务器代码:
var express = require('express');
var mongodb = require('mongodb');
var GeoJSON = require('geojson');
var strftime = require('strftime');
var router = express.Router();
var MongoClient = mongodb.MongoClient;
router.get('/query', function(req, res, next) {
    var url = "mongodb://localhost/example_db";
    var collection_name = "example_collection";
    var poi = req.query.poi ? req.query.poi.split("||") : null;
    var time = req.query.time;
    var uid = req.query.uid;
    var condition = {};
    if (poi) condition.poiname = {$in: poi};
    if (time) condition.checkin_time = {$gte:new Date(time.start_time), $lte:new Date(time.end_time)};
    if (uid) condition.uid = parseInt(uid);
    MongoClient.connect(url, function(err, db) {
        if (err) console.log('connection error');
        var collection = db.collection(collection_name);
        collection.find(condition).sort({checkin_time:1}).toArray(function(err, result) {
            if (err) {
                console.log(err);
                return res.send('error!');
            }
            if (!result) return res.send('no data');
            //This line prints the result after empty response has been sent.
            console.log(result);
            var data = {};
            data['geojson'] = GeoJSON.parse(result, {Point:'loc', include:['poiname', 'uid', 'checkin_time']});
            res.json(data);
            db.close();
    });
});

我的数据有点大,12G存储在mongodb。因此,通常需要大约3分钟或更长时间才能完成查询。当我使用findOne只检索一个文档时,这是没有问题的。

是数据大小导致的问题吗?

Try GeoJSON.parse with callback

        var data = {};
        GeoJSON.parse(result, {Point:'loc', include:['poiname', 'uid', 'checkin_time']}, function (geojson) {
            data['geojson'] = geojson;
            res.json(data);
            db.close();
        });