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 :]

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.