Express.js中获取MongoDB users集合全部内容失败问题求助
Mongoose查询users集合返回空数组或报错的解决办法
问题场景
- 执行以下代码查询
users集合,返回空数组[]:
const mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/test'); let db = mongoose.connection; const User = require('../models/userSchema'); db.collection("users").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); });
- 改用Model的
find方法查询,报错User.find(...).toArray is not a function:
User.find({}).toArray(function(err, result) { if (err) throw err; console.log(result); });
解决办法
针对返回空数组的问题
- 核心原因:Mongoose默认会将模型名转为复数作为集合名,若实际集合名不匹配,就会查不到数据;另外数据库连接是异步操作,可能查询时连接未建立完成。
- 具体修复:
- 检查MongoDB中实际的集合名称,确保和代码中
db.collection("users")的参数一致。 - 定义Schema时显式指定集合名,避免自动复数转换:
const userSchema = new mongoose.Schema( { /* 字段定义 */ }, { collection: 'users' } // 强制指定集合名 ); - 等待数据库连接成功后再执行查询:
mongoose.connect('mongodb://127.0.0.1:27017/test') .then(() => { db.collection("users").find({}).toArray((err, result) => { if (err) throw err; console.log(result); }); }) .catch(err => console.error('数据库连接失败', err));
- 检查MongoDB中实际的集合名称,确保和代码中
针对toArray is not a function报错的问题
- 核心原因:Mongoose的
Model.find()返回的是Query对象,并非MongoDB原生Cursor,因此没有toArray()方法。 - 具体修复:
- 使用Mongoose支持的回调方式获取结果:
User.find({}, (err, result) => { if (err) throw err; console.log(result); }); - 更推荐使用Promise/async-await语法:
async function fetchUsers() { try { const users = await User.find({}); console.log(users); } catch (err) { console.error('查询失败', err); } } fetchUsers();
- 使用Mongoose支持的回调方式获取结果:
内容的提问来源于stack exchange,提问作者Estban X
相关产品推荐
相关产品推荐

