我一直在尝试使用 Node.js、Express.js 和 MongoDB 创建一个简单的网站。我是这些技术的新手,并且在设置数据库时遇到了问题 这是我的 index.js 文件中的代码片段:
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var mongoHost = 'localHost';
var mongoPort = 27017;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort));
mongoClient.open(function(err, mongoClient) {
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1);
}
var db = mongoClient.db("MyDatabase");
collectionDriver = new CollectionDriver(db);
});
在我尝试在终端中运行 node index.js
后,它会显示以下内容:
js-bson: Failed to load c++ bson extension, using pure JS version
/Users/username/dev/ga-final/index.js:31
mongoClient.open(function(err, mongoClient) { //C
^
TypeError: Object #<MongoClient> has no method 'open'
at Object.<anonymous> (/Users/username/dev/ga-final/index.js:31:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
怎么了?为什么我打不开?你能帮我解决这个问题吗?谢谢!
最佳答案
发生这种情况可能是因为您使用的是新版本的 mongodb,在我使用 mongodb 驱动程序版本 1.4 后它工作正常。
npm install mongodb@1.4.x
关于javascript - Object #<MongoClient> 没有方法 'open',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626186/