【问题标题】:NodeJS and node-mongodb-nativeNodeJS 和 node-mongodb-native
【发布时间】:2010-06-17 18:37:51
【问题描述】:

刚开始使用node,并尝试获取mongo驱动程序 去工作。我已经建立了连接,奇怪的是我可以插入东西 很好,但是在集合上调用 find 会产生疯狂。

var db = new mongo.Db('things', new mongo.Server('192.168.2.6',mongo.Connection.DEFAULT_PORT, {}), {});

db.open(function(err, db) {
    db.collection('things', function(err, collection) {
//          collection.insert(row);
        collection.find({}, null, function(err, cursor) {
            cursor.each(function(err, doc) {
                sys.puts(sys.inspect(doc,true));
            });
        });

    });
});

如果我取消注释插入并注释掉查找,它会起作用。 不幸的是,逆不成立,我收到此错误:

        collection.find({}, null, function(err, cursor) {
            ^
TypeError: Cannot call method 'find' of null

我确定我在做一些愚蠢的事情,但我这辈子做不到 找到它...

【问题讨论】:

  • 我认为这意味着您遇到了错误。你能检查 'err' 的值吗?
  • 另外,我认为您在使用 new mongo.Db('things'... 'things' 是数据库名称而不是集合时使用。我不确定这是否会导致问题

标签: javascript mongodb node.js


【解决方案1】:

我刚才得到了同样的东西。我意识到由于某种原因,db.collection 被一遍又一遍地调用,所以我做了这样的事情(修改你的代码):

    var db = new mongo.Db('things', new mongo.Server('192.168.2.6',mongo.Connection.DEFAULT_PORT, {}), {});

    var Things;    

    db.open(function(err, db) {
        db.collection('things', function(err, collection) {
            Things = Things || collection;    
    });

   var findThings = function() {
       Things.find({}, null, function(err, cursor) {
           cursor.each(function(err, doc) {
               sys.puts(sys.inspect(doc,true));
           });
       });
   }

我知道你在 9 个月前问过这个问题。希望这个坟墓挖掘仍然可以帮助某人。祝你好运!

【讨论】:

    【解决方案2】:

    尝试在插入后调用 collection.save() 以刷新行。

    看看http://www.learnboost.com/mongoose/

    “目前 Mongoose 只支持手动刷新数据到服务器。”

    【讨论】:

    • Mongoose != node-mongodb-native
    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2011-06-21
    相关资源
    最近更新 更多