【问题标题】:I got an error when i retrieve data from mongodb从 mongodb 检索数据时出现错误
【发布时间】:2020-12-27 19:56:08
【问题描述】:

我正在从文档中学习 Mongodb,并在检索数据时遇到了这个问题,我无法接收到实际数据。在使用 nodejs 时

代码

const { MongoClient } = require("mongodb");


const url = "mongodb://localhost:27017/";

const client = new MongoClient(url, {
  useUnifiedTopology: true
});

const dbName = 'Test';
const run = async () => {
  try {
    await client.connect();
    const db = client.db(dbName);
    const data = db.collection('inventory').find({})
    console.log(data);
  }
  catch (err) {
    console.log(err.stack);
  }
  finally {
    await client.close();
  }
}

run().catch(console.dir);

我知道了

Cursor {
  _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
  },
    ..........
}

我不知道发生了什么,为什么我没有得到数据

【问题讨论】:

  • const data = db.collection('inventory').find({})应该是const data = await db.collection('inventory').find({}).toArray()

标签: javascript node.js mongodb


【解决方案1】:

您没有收到错误消息。你得到一个 MongoDB 游标。 .find() 是异步的,它返回数据的 Promise,而不是直接返回数据。你需要等待它:

const data = await db.collection('inventory').find({});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2018-11-16
    • 2019-06-14
    相关资源
    最近更新 更多