Mongoose 是一个用于 Node.js 的对象文档映射(ODM)库,它提供了一种直接的方式来在 Node.js 应用程序中使用 MongoDB 数据库。当使用 Mongoose 查询数据库时,有时可能会遇到返回空数组的情况,即使数据库中存在匹配的文档。这种情况可能由以下几个原因造成:
// 错误的查询条件
const result = await Model.find({ name: '' }); // 这里应该是一个具体的名字
// 确保数据库连接正常
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
// 确保模型定义正确
const modelSchema = new mongoose.Schema({
name: String,
age: Number
});
const Model = mongoose.model('Model', modelSchema);
// 为查询字段创建索引
Model.collection.createIndex({ name: 1 });
解决方法:
示例代码:
const mongoose = require('mongoose');
// 连接到 MongoDB
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
// 定义模型
const modelSchema = new mongoose.Schema({
name: String,
age: Number
});
const Model = mongoose.model('Model', modelSchema);
// 创建索引
Model.collection.createIndex({ name: 1 });
// 正确的查询条件
const result = await Model.find({ name: 'John' }).exec();
console.log(result);
如果上述方法都不能解决问题,可以尝试使用 Model.find().lean().exec()
来获取非 Mongoose 文档对象,这样可以排除 Mongoose 的中间件或虚拟属性影响查询结果。
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云