MongoDb 查询 return 空对象

MongoDb query return empty object

我正在尝试在我的 mongodbAtlas 上执行一个简单的 .find() 查询,但该查询的结果是一个空对象。

这是我的服务器文件:

require("dotenv").config({ path: "./config.env" });
const { MongoClient, ServerApiVersion } = require("mongodb");
const express = require("express");
const { ServiceBroker } = require("moleculer");
const AUTH_SERVICE = require("./controller/services/auth/auth.service");

global.broker = new ServiceBroker({
  nodeID: "auth",
});

const app = express();
app.use(express.json());
app.use("/auth", require("./routes/auth"));

const { PORT, URI } = process.env || 5000;

global.broker.createService(AUTH_SERVICE);

const start = async () => {
  const dba = await MongoClient.connect(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  global.db = dba.db("Auth");

  try {
    await dba.connect();
    console.log("DATABASE CONNESSO CON SUCCESSO");
  } catch (e) {
    console.error(e);
  }

  await global.broker.start();
  app.listen(PORT, () => console.log(`PORT IT'S UP AND RUNNING  ON ${PORT}`));
};
start();

这是我的路线文件:

const express = require("express");
const router = express.Router();

router.get("/register", async (req, res) => {
  const data = global.db.collection("Users").find({}).toArray();
  res.send(data);
});


module.exports = router;

我的文档是这样填充的:

{"_id":{"$oid":"6297bbc83a95b81d74882f65"},"username":"Test","email":"test@gmail.com","password":"1234"}

我认为您在 const data 之后缺少“await”关键字......因为 API 数据获取调用是异步的并且需要 promise/ async-await 来处理。本质上是异步的,它前进到下一条指令和returns一个空数组。

const express = require("express");
const router = express.Router();

router.get("/register", async (req, res) => {
const data = await global.db.collection("Users").find({}).toArray();
  res.send(data);
});

module.exports = router;