对象#<mongoclient>没有方法'open'</mongoclient>

时间:2014-10-29 09:00:54

标签: javascript node.js mongodb express database

我一直试图用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

有什么问题?为什么我打不开?你能帮我解决这个问题吗?谢谢!

2 个答案:

答案 0 :(得分:14)

发生这种情况可能是因为你使用mongodb的新版本,在我使用mongodb驱动程序版本1.4之后它工作正常。

npm install mongodb@1.4.x

答案 1 :(得分:8)

看看mongodb docs。您的mongoClient对象不是您认为的那样,也就是没有open()方法可用的原因。

让您的示例代码看起来更像他们的代码:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  db.close();
});