问题:使用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版本
解决方法:
- 使用npm降低MongoDB的版本
npm install mongodb@2.x - 修改代码,使用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();
});
}
MongoDB升级与适配:解决连接错误TypeError: db.collection is not a function
本文讲述了在使用MongoDB 2.0旧版本代码连接数据库时遇到的TypeError,并提供了解决方法,包括如何通过npm降级到2.x版本以及代码语法的调整。
534

被折叠的 条评论
为什么被折叠?



