Mongoose使用无效$exists查询返回全部记录问题求助
问题分析与解决方案
这是Mongoose默认的strictQuery行为导致的问题:Mongoose 6及以上版本默认开启strictQuery,会自动过滤掉查询条件中Schema未定义的字段。
你的users Schema里没有sharedWith字段,所以Mongoose处理$or查询时直接移除了{ sharedWith: { $exists: true } }这个条件,导致查询逻辑偏离预期,最终返回了所有用户记录(本质是无效的查询条件被过滤后,实际执行的查询匹配了全部文档)。
以下是三种可行的解决方案:
方案1:查询时临时禁用strict模式
在find方法的选项参数中添加strict: false,允许查询Schema未定义的字段:
const users = await userModel.find( { $or: [{ _id: '631f0f3b40548b9388d96998' }, { sharedWith: { $exists: true } }] }, null, { strict: false } );
方案2:全局关闭strictQuery
如果你的业务需要频繁查询Schema外的字段,可以在Mongoose连接前全局修改配置:
mongoose.set('strictQuery', false); mongoose.connect('mongodb://localhost:27017/your-database-name');
方案3:在Schema中声明sharedWith字段(可选)
如果sharedWith字段可能偶尔出现在users集合中,可以在Schema里将其定义为可选字段,避免Mongoose过滤相关查询条件:
const userSchema = new mongoose.Schema({ email: String, sharedWith: { type: mongoose.Schema.Types.Mixed, required: false } });
以上方案均可让你的$or查询和MongoDB Shell中的行为一致,仅返回匹配_id或存在sharedWith字段的用户记录。
内容的提问来源于stack exchange,提问作者Roo
相关产品推荐
相关产品推荐

