【问题标题】:Cannot retrieve all entries from MongoDB collection无法从 MongoDB 集合中检索所有条目
【发布时间】:2022-01-13 18:31:28
【问题描述】:

我正在尝试从 mongo 检索所有条目,但我不断收到一个错误,在有一些条目时我找不到任何错误。

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';

tryMongo();

function tryMongo() {
  MongoClient.connect(url, (err, client) => {
    if (err) return console.log('Cannot connect to DB');
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection('toy');
    collection.find().toArray((err, docs) => {
      if (err) return console.log('cannot find toys');
      console.log('found these:');
      console.log(docs);
    });
    client.close();
  });
}

这是我遇到的错误: 服务器监听 3030 端口! 成功连接到服务器 找不到玩具

我还加了一张mongo的图片

感谢任何形式的帮助!

【问题讨论】:

  • console.log(err) 你就会知道问题所在

标签: javascript node.js mongodb


【解决方案1】:

在收到服务器响应之前,您正在关闭 mongo 连接。将client.close(); 移动到toArray 回调中。

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';

tryMongo();

function tryMongo() {
  MongoClient.connect(url, (err, client) => {
    if (err) return console.log(err);
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection('toy');
    collection.find().toArray((err, docs) => {
      if (err) {
        console.log(err);
      } else {
        console.log('found these:');
        console.log(docs);
      }
      client.close();
    });
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2019-07-11
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多