MongoDB连接数据库时报错TypeError: db.collection is not a function
问题:使用MongoDB连接数据库时报错TypeError: db.collection is not a function代码如下:var find = function (db, collections, selector, fn) {var collection = db.collection(collections);collection.find(selector).toArray(fu
·
问题:使用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();
});
}
更多推荐
已为社区贡献3条内容
所有评论(0)