Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mongoDB with node

When I run the script, the error returns.

TypeError: db.collection is not a function

 var MongoClient = require('mongodb').MongoClient;
 var url = "mongodb://abc:12345**@xxxx.mlab.com:&&&&/myDB";
 MongoClient.connect(url, function(err, db) {
   if(err) {
      console.log(err);
   } else {
      console.log("Database created!");
      db.collection('users').aggregate([{
        '$match': {
          'organization.organizationId': "e1716c62-fdce-11e7-8be5-
           0ed5f89f718b"
        }
      },{
       "$project": {
          "deviceDetails": 1,
          "userDetails": 1
       }
     }], function(error, documents) {
           if (error) {
             console(error);
           } else {
           console.log(documents);
          }
        });
  });

Hi, could you please help me where am I doing wrong.Thanks!

like image 747
Rahul Saini Avatar asked Feb 10 '26 17:02

Rahul Saini


1 Answers

With Mongo Driver 3.0 or above, the connect callback returns err and client instead of db. To get the db out of the client do this,

var db = client.db;

In your case, it will look something like this,

MongoClient.connect(url, function(err, client) {
   if(err) {
    console.log(err);
   } else {
      var db = client.db;
      console.log("Database created!");
      db.collection('users').aggregate(...)
   }
})
like image 174
Nilesh Singh Avatar answered Feb 13 '26 10:02

Nilesh Singh