无法读取null的属性'collection'(CosmosDB + mongo + node)

时间:2018-01-18 14:08:23

标签: node.js mongodb azure azure-cosmosdb

我关注此事:https://docs.microsoft.com/en-us/azure/cosmos-db/mongodb-samples

这是代码:

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();
        });
    });
    });
});
});

我一直收到此错误:

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

TypeError: Cannot read property 'collection' of null

数据库在我使用robomongo进行测试时有效,但不会与nodeJS连接。 我试过重置密码并从azure portal创建新的cosmosDB,一切似乎都没问题。

1 个答案:

答案 0 :(得分:1)

对于node-mongodb-native的最新版本(v3.0.1),您需要使用此语法连接到MongoDB,如下所示:

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();
        });
      });
    });
  });
});

对于Mongoose(v5.0.1),您可以使用以下代码创建连接:

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));