问题:使用MongoDB连接数据库时报错TypeError: db.collection is not a function

代码如下:

var find = function (db, collections, selector, fn) {
  var collection = db.collection(collections);

  collection.find(selector).toArray(function (err, result) {
    //console.log(docs);
    try {
      assert.equal(err, null);
    } catch (e) {
      console.log(e);
      result = [];
    }

    fn(result);
    db.close();
  });

}

问题原因:
MongoDB 2.0与3.0以上版本语法不同;代码中使用的是MongoDB 2.0的写法,而安装时npm默认安装最新版本,即3.0版本

解决方法:

  1. 使用npm降低MongoDB的版本
    npm install mongodb@2.x
  2. 修改代码,使用3.0版本的语法,以下为修改后代码,具体示例可从node_modules\mongodb\lib\collection.js文件查看
var find = function (client, collections, selector, fn) {
  // var collection = db.collection(collections);
  var collection = client.db(dbName).collection(collections)

  collection.find(selector).toArray(function (err, result) {
    //console.log(docs);
    try {
      assert.equal(err, null);
    } catch (e) {
      console.log(e);
      result = [];
    }

    fn(result);
    client.close();
  });

}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐