【问题标题】:Cannot read property 'collection' of null无法读取 null 的属性“集合”
【发布时间】:2016-12-13 07:38:25
【问题描述】:

这是我的代码

// 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) {});

});

它正在显示此错误“无法读取 null 的属性 'collection'”。

【问题讨论】:

  • 你查看err的内容了吗?
  • 否,如何查看?我是 Node.js 的初学者,只是想将它连接到 mongodb。
  • 这样做:if (err) {console.error(err); }
  • 不要让nodejs代码在浏览器中作为可执行文件是徒劳的!
  • 您是否将代码作为“node filename.js”运行?上面的代码对我来说很好。我使用命令“node ”运行了代码。文档也插入成功。

标签: node.js mongodb


【解决方案1】:

问题是无论数据库连接是否成功,您都直接调用 db.collection。您需要检查db连接是否有错误。 db.collection 仅在数据库连接成功时起作用。查看以下示例以更好地理解

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

})

【讨论】:

    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2021-05-11
    • 2016-11-24
    相关资源
    最近更新 更多