You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MERN教程报错:Cannot read properties of undefined (reading 'collection')

MERN项目数据库连接报错排查问题

问题背景

  • 跟着MongoDB MERN教程开发,当前端尝试连接数据库拉取文档时出现报错
  • 拉取官方仓库代码并填入自身连接信息后可正常运行,两者差异仅为官方代码使用了教程未提及的mongoose,且包版本更旧
  • npm版本:9.4.1

报错信息

$ npm start

> server@1.0.0 start
> node server.js

Server is running on port: 5000
TypeError: Cannot read properties of undefined (reading 'collection')
    at D:\MERN\mine\server\routes\record.js:19:6
    at Layer.handle [as handle_request] (D:\MERN\mine\server\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\MERN\mine\server\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (D:\MERN\mine\server\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (D:\MERN\mine\server\node_modules\express\lib\router\layer.js:95:5)
    at D:\MERN\mine\server\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (D:\MERN\mine\server\node_modules\express\lib\router\index.js:346:12)
    at next (D:\MERN\mine\server\node_modules\express\lib\router\index.js:280:10)
    at Function.handle (D:\MERN\mine\server\node_modules\express\lib\router\index.js:175:3)
    at router (D:\MERN\mine\server\node_modules\express\lib\router\index.js:47:12)

关键报错代码(record.js第19行)

// This section will help you get a list of all the records.
recordRoutes.route("/record").get(function (req, res) {
  let db_connect = dbo.getDb("employees");
  db_connect
    .collection("records")
    .find({})
    .toArray(function (err, result) {
      if (err) throw err;
      res.json(result);
    });
});

排查情况

  • 已确认连接凭证正常,可在MongoDB Compass及官方仓库中验证
  • 添加多个console.log排查时,server.js第14行的connectToServer匿名函数内日志从未触发

相关代码文件

server.js

const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");

app.listen(port, () => {
  // perform a database connection when server starts
  dbo.connectToServer(function (err) {
    if (err) console.error(err);

  });
  console.log(`Server is running on port: ${port}`);
});

record.js(部分代码)

const express = require("express");

// recordRoutes is an instance of the express router.
// We use it to define our routes.
// The router will be added as a middleware and will take control of requests starting with path /record.
const recordRoutes = express.Router();

// This will help us connect to the database
const dbo = require("../db/conn");

// This help convert the id from string to ObjectId for the _id.
const ObjectId = require("mongodb").ObjectId;


// This section will help you get a list of all the records.
recordRoutes.route("/record").get(function (req, res) {
  let db_connect = dbo.getDb("employees");
  db_connect
    .collection("records")
    .find({})
    .toArray(function (err, result) {
      if (err) throw err;
      res.json(result);
    });
});

修改后的conn.js

const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

let _db;

module.exports = {
  connectToServer: async function (callback) {
    console.log("test");

    try {
      await client.connect();
    } catch (e) {
      console.error(e);
    }

    _db = client.db("employees");

    try {
      var count = await _db.collection("records").countDocuments();
      console.log(count);
    } catch (e) {
      console.error(e);
    }

    if(_db !== undefined){
      return true;
    }
  },
  getDb: function () {
    return _db;
  },
};

尝试过的解决方案

  • 在服务端安装mongoose(npm install mongoose),但问题未解决
  • 修改conn.js使用async/await后,可获取employees集合的记录计数,但React前端路由无法正常工作且无报错

内容的提问来源于stack exchange,提问作者FrankT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:50:27