armaan kohli
armaan kohli

Reputation: 41

Cannot read property 'collection' of null

Here is my code

// Retrieve
var MongoClient = require('mongodb').MongoClient;

// Connect to the db

MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) { 
     console.log('we are connected'); 
  }

  var k ='testt';
  var collection = db.collection(k);
  var doc1 = {'hello':'doc1'};
  var doc2 = {'hello':'doc2'};
  var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];

  collection.insert(doc1);

  collection.insert(doc2, {w:1}, function(err, result) {});

  collection.insert(lotsOfDocs, {w:1}, function(err, result) {});

});

and it is is showing this error "Cannot read property 'collection' of null".

Upvotes: 4

Views: 14029

Answers (1)

Prerak Shrivastava
Prerak Shrivastava

Reputation: 31

The issue is you are directly calling db.collection irrespective of whether db connection is successful or not. You need to check whether there is an error in db connection. db.collection works only when the DB connection is successful. Check below example for better understanding

 MongoClient.connect('mongodb://localhost:27017/test',function(err,db){
    if(err)
    {
        console.log(err);
    }
    else
    {
        console.log("Connected to db");

        db.collection('testt').insert({"doc1":"hello"},function(err,data){

      if(err)
    {
      throw(err);
    }
    else
    {
     console.log("sucessfuly inserted");
    }

})

Upvotes: 3

Related Questions