Object # <MongoClient> has no 'open' method
I tried to create a simple site with Node.js, Express.js and MongoDB. I am new to these technologies and I had a problem setting up the database Here is a snippet of code in the index.js file:
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); }); After I try to run node index.js in the terminal, it says the following:
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 What's wrong? Why can't I open? Can you help me fix this? thanks!
+6
2 answers
Take a look at the mongodb docs . Your mongoClient object is not what you think, and why the open() method does not exist.
Make your sample code more like them:
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(); }); +5