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

MongoDB 3.x语法查询数据库未获取目标文档的问题排查

问题分析与解决方案

我帮你排查出了几个核心问题,咱们逐个解决:


1. 数据库名称大小写不匹配

MongoDB默认是区分数据库名称大小写的!你在Mongo Shell里确认的是iRateIt库(小写i开头),但代码里却用了client.db("IRateIt")(大写I开头)——这直接导致你连接到了一个不存在的空数据库,自然查不到任何数据。

2. 查询条件完全没生效

你明明定义了query = {isActive: true},但实际调用collection.find({})时用了空对象,等于查询所有文档(而且因为库不对,就算查所有也返回空)。

3. 函数定义顺序错误

你在调用findDocuments(db, ...)之后才定义这个函数——JavaScript里的函数表达式(const xx = function(){})不会被提升,调用时函数还不存在,这会导致查询逻辑根本没执行(或者报错)。

4. 没给前端返回响应

你的路由只做了数据库查询,但没把结果通过res返回给客户端,就算查询成功前端也拿不到数据。

5. 冗余的Mongoose连接

你同时用了原生MongoClient和Mongoose连接数据库,这不仅没必要,还可能导致连接混乱,先把Mongoose的代码去掉,统一用原生客户端。


修复后的完整代码

const express = require('express');
const app = express();
const assert = require('assert');
const port = 4000;
const MongoClient = require('mongodb').MongoClient;
// 统一数据库名称为iRateIt(和Mongo Shell一致)
const url = "mongodb://localhost:27017/iRateIt";

// 先定义查询函数,确保调用前已存在
const findDocuments = function(db, callback) {
  const query = {isActive: true};
  const collection = db.collection('professors');
  // 使用定义好的查询条件
  collection.find(query).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });
}

app.use("/",(req,res) => {
  MongoClient.connect(url, function(err, client){
    assert.equal(null, err);
    console.log("Connected successfully to server");
    // 连接正确的数据库
    const db = client.db("iRateIt");
    findDocuments(db, function(docs) {
      // 给前端返回查询结果
      res.json({success: true, data: docs});
      client.close();
    });
  });
});

// 别忘了启动服务器监听端口
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

最后验证步骤

  1. 确保MongoDB服务正在运行(端口27017)
  2. 打开Mongo Shell,执行:
    use iRateIt
    db.professors.find({isActive: true})
    
    确认能返回预期的文档
  3. 重启你的Express服务,重新请求路由,现在应该能拿到正确的数据了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:52:51