Node.JS查询MongoDB返回null

时间:2016-02-19 15:21:37

标签: javascript node.js mongodb

我是 Node.js MongoDB 的新手,我正在尝试。

我创建了一个名为footIco的集合。 当我使用db.footIco.find()在控制台中查询 MongoDB 时,它会返回所有数据。

但是,当我从 Node.js 查询 MongoDB 时,它不会返回任何数据。

我可以在 MongoDB 服务器控制台中看到连接。

这是我的 Node.js 脚本;

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/footIco';

var findIco = function(db, callback) {
   var cursor =db.collection('footIco').find();
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
           console.dir(doc);
      }
   });
};

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  findIco(db, function() {
      db.close();
  });
});

有谁能告诉我这有什么问题。它几乎是来自 MongoDB 教程

的复制和粘贴

1 个答案:

答案 0 :(得分:1)

这一行:

assert.equal(err, null);

它是特定于JavaScript的,抛出错误的处理程序将无处可去,我建议将其更改为console.log(err)或仅修改回调以处理err参数。