Sushant Shekhar
Sushant Shekhar

Reputation: 97

Cannot read property 'collection' of null (CosmosDB+mongo+node)

I am following this: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb-samples

here is the code :

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://<endpoint>:<`enter code `enter code here`here`password>@<endpoint>.documents.azure.com:10255/?ssl=true';

var insertDocument = function(db, callback) {
db.collection('families').insertOne( {
        "id": "AndersenFamily",
        "lastName": "Andersen",
        "parents": [
            { "firstName": "Thomas" },
            { "firstName": "Mary Kay" }
        ],
        "children": [
            { "firstName": "John", "gender": "male", "grade": 7 }
        ],
        "pets": [
            { "givenName": "Fluffy" }
        ],
        "address": { "country": "USA", "state": "WA", "city": "Seattle" }
    }, function(err, result) {
    assert.equal(err, null);
    console.log("Inserted a document into the families collection.");
    callback();
});
};

var findFamilies = function(db, callback) {
var cursor =db.collection('families').find( );
cursor.each(function(err, doc) {
    assert.equal(err, null);
    if (doc != null) {
        console.dir(doc);
    } else {
        callback();
    }
});
};

var updateFamilies = function(db, callback) {
db.collection('families').updateOne(
    { "lastName" : "Andersen" },
    {
        $set: { "pets": [
            { "givenName": "Fluffy" },
            { "givenName": "Rocky"}
        ] },
        $currentDate: { "lastModified": true }
    }, function(err, results) {
    console.log(results);
    callback();
});
};

var removeFamilies = function(db, callback) {
db.collection('families').deleteMany(
    { "lastName": "Andersen" },
    function(err, results) {
        console.log(results);
        callback();
    }
);
};

MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
    findFamilies(db, function() {
    updateFamilies(db, function() {
        removeFamilies(db, function() {
            db.close();
        });
    });
    });
});
});

I keep getting this Error :

db.collection('families').insertOne( {
   ^

TypeError: Cannot read property 'collection' of null

The Database works when I test with robomongo, but won't connect with nodeJS. I have tried resetting the password and creating new cosmosDB from azure portal, everything seems to be alright.

Upvotes: 0

Views: 1094

Answers (1)

Aaron Chen
Aaron Chen

Reputation: 9950

For the latest version (v3.0.1) of node-mongodb-native, you'll need to use this syntax to connect to MongoDB like this:

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://<endpoint>.documents.azure.com:10255/?ssl=true';

// ...

MongoClient.connect(url, { 
  auth: {
    user: '<endpoint>',
    password: '<password>'
  }
}, function(err, client) {
  assert.equal(null, err);

  var db = client.db('<dbname>');

  insertDocument(db, function() {
    findFamilies(db, function() {
      updateFamilies(db, function() {
        removeFamilies(db, function() {
          client.close();
        });
      });
    });
  });
});

For Mongoose (v5.0.1), you can create a connection by using following code:

const mongoose = require('mongoose');

mongoose.connect('mongodb://<endpoint>.documents.azure.com:10255/databasename?ssl=true', {
    auth: {
      user: '<endpoint>',
      password: '<password>'
    }
  })
  .then(() => console.log('connection successful'))
  .catch((err) => console.error(err));

Upvotes: 1

Related Questions