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

Mongoose查询始终返回空数组,但数据库存在对应记录的问题排查

问题排查与解决方案

核心问题1:未指定目标数据库

你的连接字符串中没有明确指定要连接的数据库名称,Mongoose会默认连接到test数据库,但你的authors集合大概率不在这个库中,这是查询返回空数组的首要原因。

修改连接字符串,在末尾添加你的实际数据库名称:

const connectionString = `mongodb+srv://mkreyn:${password}@youtube-base.7mpecw5.mongodb.net/你的数据库名称?retryWrites=true&w=majority`;

核心问题2:连接未就绪就执行查询

connectDB函数没有返回Promise,await connectDB()并不会等待数据库连接真正建立就执行getRecords,导致查询时连接还未就绪。

将connectDB改为异步函数,确保等待连接完成:

const connectDB = async () => {
    const password = 'my-password-here-masked';
    // 替换为你的实际数据库名称
    const connectionString = `mongodb+srv://mkreyn:${password}@youtube-base.7mpecw5.mongodb.net/你的数据库名?retryWrites=true&w=majority`;

    const clientOptions = { serverApi: { version: '1', strict: true, deprecationErrors: true } };
   
    try {
      await mongoose.connect(connectionString, clientOptions);
      const dbConnection = mongoose.connection;
      dbConnection.once("open", (_) => {
        console.log(`Database connected: ${connectionString}`);
      });
     
      dbConnection.on("error", (err) => {
        console.error(`connection error: ${err}`);
      });
    } catch (err) {
      console.error(err.message);
      process.exit(1);
    }
}

其他优化与验证点

  • 不要在函数内重复定义Model:Mongoose的Model应该全局定义一次,重复定义会导致异常。把Schema和Model移到文件顶部:
    const mongoose = require('mongoose')
    
    // 全局定义Schema与Model
    const AuthorsSchema = new mongoose.Schema({
      _id: mongoose.Schema.Types.ObjectId,
      author_name: String,
      author_country: String
    });
    
    const AuthorsModel = mongoose.model("authors", AuthorsSchema);
    
  • 验证字段值的精确性:确认数据库中author_country字段的值是精确的"UK"(注意大小写、空格,比如是否存在"uk"或" UK "这类格式差异)。

修改后的完整代码示例:

const mongoose = require('mongoose')

// 全局定义Schema与Model
const AuthorsSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  author_name: String,
  author_country: String
});

const AuthorsModel = mongoose.model("authors", AuthorsSchema);

const connectDB = async () => {
    const password = 'my-password-here-masked';
    // 替换为你的实际数据库名称
    const connectionString = `mongodb+srv://mkreyn:${password}@youtube-base.7mpecw5.mongodb.net/你的数据库名?retryWrites=true&w=majority`;

    const clientOptions = { serverApi: { version: '1', strict: true, deprecationErrors: true } };
   
    try {
      await mongoose.connect(connectionString, clientOptions);
      const dbConnection = mongoose.connection;
      dbConnection.once("open", (_) => {
        console.log(`Database connected: ${connectionString}`);
      });
     
      dbConnection.on("error", (err) => {
        console.error(`connection error: ${err}`);
      });
    } catch (err) {
      console.error(err.message);
      process.exit(1);
    }
}

const getRecords = async () => {
  try {
    const allRecs = await AuthorsModel.find({author_country: "UK" }).exec();
    console.log(allRecs);
  } catch (error) {
    console.error('Error fetching records:', error);
  } finally {
    await mongoose.connection.close();
  }
}

const greatFunc = async () => {
  await connectDB();
  await getRecords();
}

greatFunc();

内容的提问来源于stack exchange,提问作者m.kreyn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:22:31