我似乎无法使用Node.js从mongodb检索数据

时间:2013-09-11 15:06:06

标签: node.js node-mongodb-native

我无法从mongodb集合中检索数据,我认为这些数据已正确插入。

所以这是我的示例代码......

var db = require('./database');

module.exports = function (app) {
    app.get('/db', function (req, res) {
        db.collection('myCollection', function (err, myCollection) {
            if (err) {
                return console.error(err);
            }

            var docrow = {
                // no id specified, we'll let mongodb handle that
                name: 'Mark',
                date: '2013/09/11',
                description: 'Some text here'
            };

            console.log('I GET HERE OK');

            myCollection.insert(docrow, { safe: true }, function (err, insertedDocument) {
                console.log('BUT I DONT GET HERE?');

                if (err && err.name === 'MongoError' && err.code === 11000) {
                    return console.log('This document already exists');
                } else if (err) {
                    return console.log('Something bad happened');
                }

                myCollection.find({ name: 'Mark' }, function (err, docs) {
                    docs.each(function (err, doc) {
                        console.log(doc);
                    });
                });
            });


            res.end('OK we made it');
        });
    });
};

...而且database.js文件是......

var Db         = require('mongodb').Db,
    Connection = require('mongodb').Connection,
    Server     = require('mongodb').Server;

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;

/*
    w:1 tells mongo to wait until at least one confirmed write has succeeded before calling any callbacks
 */
var flags = { w: 1 };
var server = new Server(host, port, { auto_reconnect: true, poolSize: 20 });
var db = new Db('TestDBName', server, flags);

module.exports = db;

看起来我能够无错误地创建一个集合(myCollection),并且在集合上调用insert也没有错误,但似乎也没有得到任何地方在回调函数内部附近是为了触发错误还是处理成功?

我在这里做错了什么?

感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:1)

连接到mongodb时,它是异步方法,因此它将在回调中返回客户端处理程序,并且必须使用此client处理程序而不是该Db对象的句柄。所以改变这个:

var db = new Db('TestDBName', server, flags);

对此:

new Db('TestDBName', server, flags).open(function(err, client) {
  if(err) throw err;

  // client - is the guy you are looking for instead of `db` you had
});

同样改变:

myCollection.find({ name: 'Mark' }, function (err, docs) {

要:

myCollection.find({ name: 'Mark' }).toArray(function (err, docs) {

这是mongo-native的唯一例外,你必须使用.toArray而不是直接回调。