0

我无法从我认为已正确插入的 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;

看起来我能够创建一个集合myCollectioninsert处理成功?

我在这里做错了什么?

感谢你给与我的帮助。

4

1 回答 1

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而不是直接回调。

于 2013-09-11T15:12:43.967 回答