寻找有关在Node.JS中从MongoDB读取的帮助

问题描述:

我在MongoDB中存储了许多记录,我试图通过Node.JS http服务器将它们输出到浏览器窗口.我认为我在整个过程中都占了很大一部分,但是我错过了一些小事情,这些事情使它无法正常工作.

I have a number of records stored in a MongoDB I'm trying to output them to the browser window by way of a Node.JS http server. I think I'm a good portion of the way along but I'm missing a few little things that are keeping it from actually working.

下面的代码使用node-mongo-native连接到数据库.

The code below uses node-mongo-native to connect to the database.

如果周围有人可以帮助我在节点上进行最后的几次联系,我将非常感激.公平地说,我敢肯定这仅仅是个开始.

If there is anyone around who can help me make those last few connections with working in node I'd really appreciate it. To be fair, I'm sure this is just the start.

var sys  = require("sys");
var test = require("assert");
var http = require('http');

var     Db              = require('../lib/mongodb').Db,
        Connection      = require('../lib/mongodb').Connection,
        Server          = require('../lib/mongodb').Server,
        //BSON          = require('../lib/mongodb').BSONPure;
        BSON            = require('../lib/mongodb').BSONNative;

var     host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var     port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;

sys.puts("Connecting to " + host + ":" + port);

function PutItem(err, item){
    var result = "";
    if(item != null) {
            for (key in item) {
                    result += key + '=' + item[key];
            }
    }
    // sys.puts(sys.inspect(item))  // debug output
    return result;
}

function ReadTest(){
    var db = new Db('mydb', new Server(host, port, {}), {native_parser:true});
    var result = "";
    db.open(function (err, db) {
            db.collection('test', function(err, collection) {
                    collection.find(function (err, cursor){
                            cursor.each( function (err, item) {
                                    result += PutItem(err, item);
                            });
                    });
            });
    });
    return result;
}

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end("foo"+ReadTest());
}).listen(8124);
console.log('Server running on 8124');

来源: -mongo连接代码: https://github.com/christkv/node-mongodb -native/blob/master/examples/simple.js -节点. http代码:nodejs.org

Sources: - mongo connectivity code: https://github.com/christkv/node-mongodb-native/blob/master/examples/simple.js - node. http code: nodejs.org

编辑更正的代码

感谢下面的麦克风使我朝着正确的方向前进.对于任何有兴趣的人,更正的解决方案都在这里:

Thanks to Mic below who got me rolling in the right direction. For anyone interested, the corrected solution is here:

function ReadTest(res){
    var db = new Db('mydb', new Server(host, port, {}), {native_parser:true});
    var result = "";
    res.write("in readtest\n");
    db.open(function (err, db) {
            res.write("now open\n");
            db.collection('test', function(err, collection) {
                    res.write("in collection\n");
                    collection.find(function (err, cursor){
                            res.write("found\n");
                            cursor.each( function (err, item) {
                                    res.write("now open\n");
                                    var x = PutItem(err, item);
                                    sys.puts(x);
                                    res.write(x);
                                    if (item == null) {
                                            res.end('foo');
                                    }
                            });
                    });
            });
    });
}

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write("start\n");
    ReadTest(res);
}).listen(8124);
console.log('Server running on 8124');

我的猜测是您正在返回结果,编写响应并在从数据库中获取任何内容之前关闭连接.

My guess is that you are returning result, writing the response, and closing the connection before anything is fetched from the db.

一种解决方案是将响应对象传递到您实际需要的地方,例如:

One solution would be to pass the response object to where you actually need it, something like:

function readTest(res) {
    db.open(function (err, db) {
        db.collection('test', function(err, collection) {
            collection.find(function (err, cursor) {
                res.writeHead(200, {'Content-type' : 'text/plain'});
                cursor.each( function (err, item) { res.write(item); });
                res.end();
     ...

当然,您还应该处理错误并尝试避免嵌套过多的级别,但这是不同的讨论.

Of course, you should also handle errors and try to avoid nesting too many levels, but that's a different discussion.