【问题标题】:Uncaught TypeError: Cannot read property 'collection' of null未捕获的类型错误:无法读取 null 的属性“集合”
【发布时间】:2021-05-11 11:43:54
【问题描述】:

我一直在尝试从集合中获取数据,但它返回了 Uncaught TypeError: Cannot read property 'collection' of null。 Mongo 数据库本身与云连接,并从那里检查具有该名称的集合是否存在。

    var output = [];

mongoose.connect(MongoURI, { useNewUrlParser: true, useUnifiedTopology: true }, function(client) {
    var cursor = client.collection('updates').find();
    cursor.forEach(function(values) {
        output += values;
    });
});

我计划稍后使用输出进行条件检查,看看是否有任何类似的条目。

【问题讨论】:

    标签: javascript node.js database mongoose mongodb-query


    【解决方案1】:

    正如官方文档所述,mongoose.connect 接受回调作为最后一个参数来处理错误。 https://mongoosejs.com/docs/4.x/docs/connections.html

    所以要查找数据,您应该将模型名称及其架构传递给 mongoose.model,检索集合, 然后寻找你需要的东西。例如:

    const client = mongoose.model("Client", clientScheme);
    
    client.find({}, function(err, docs){
        mongoose.disconnect();
        
        if(err) return console.log(err);
        
        console.log(docs);
    });
    

    看一眼https://mongoosejs.com/docs/guide.html

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 1970-01-01
      • 2022-01-19
      • 2021-12-01
      • 2022-07-02
      • 2022-06-14
      • 2022-10-23
      • 2023-03-05
      相关资源
      最近更新 更多