NodeJS和node-mongodb-native

use*_*680 6 javascript mongodb node.js

刚刚开始使用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));
            });
        });

    });
});
Run Code Online (Sandbox Code Playgroud)

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

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

我确定我做的事情很傻,但对于我的生活,我找不到它......

foo*_*bar 9

我刚才也有同样的事情.我意识到由于某种原因,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));
           });
       });
   }
Run Code Online (Sandbox Code Playgroud)

我意识到你9个月前问了这个问题.希望这个严重的挖掘仍然可以帮助某人.祝好运!


小智 -2

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

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

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

  • `Mongoose!= 节点-mongodb-native` (5认同)