0

I am trying to write a piece of code to connect to mongodb database from node.js using the 'mongodb' library.

here is a piece of code describing what im trying to achieve:

var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
assert = require('assert'); 
var User = require('mongo-bcrypt-user');

// Set up the connection to the local db
var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});
var db = mongoclient.db("test");
var coll = db.collection('users');

when trying to run the file im getting the following error:

D:\mongodb.js:15
var db = mongoclient.db("test");
                   ^
TypeError: undefined is not a function
at Object.<anonymous> (D:\Backups\C Drive New Backup\temp\mongodb.js:15:24)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (D:\Backups\C Drive New Backup\temp\MyWebAPI.js:8:20)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)

Thanks in advance :]

  • There are [documentation](http://mongodb.github.io/node-mongodb-native/2.0/api/) examples to this. And reading them and other nodejs related things should at least tip to you that this is "asynchronous programming". – Blakes Seven Aug 14 '15 at 09:09
  • 1
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Blakes Seven Aug 14 '15 at 09:10

1 Answers1

2

MongoClient doesn't have db method: http://mongodb.github.io/node-mongodb-native/2.0/api/MongoClient.html

It has connect(url, options, callback) method, where callback is connectCallback(error, db) function, so your code must look like this:

var mongoclient = new MongoClient('mongodb://localhost:27017',      
                                  {native_parser: true}, 
                                  function(error, db) {
                                    // use db here
                                  });

Pay attention to concepts of asynchronous programming in JavaScript. Namely callback and promises.

krl
  • 5,087
  • 4
  • 36
  • 53