MongoDB在VS中运行异常,Mongoose strictQuery弃用警告求助
解决Mongoose strictQuery弃用警告问题
[MONGOOSE] DeprecationWarning: Mongoose: the
strictQueryoption will be switched back tofalseby default in Mongoose 7. Usemongoose.set('strictQuery', false);if you want to prepare for this change. Or usemongoose.set('strictQuery', true);to suppress this warning.
(Usenode --trace-deprecation ...to show where the warning was created)
两种解决方法:
方案1:适配Mongoose 7的默认行为(推荐)
在数据库连接代码的最开头添加配置,提前适配未来版本的默认设置:const mongoose = require('mongoose'); mongoose.set('strictQuery', false); // 执行数据库连接 mongoose.connect('你的MongoDB连接URI') .then(() => console.log('数据库连接成功')) .catch(err => console.error('连接失败:', err));此设置允许查询返回Schema中未定义的字段,和Mongoose 7的默认行为一致,避免后续升级出现兼容问题。
方案2:保持现有行为并抑制警告
若想维持当前版本的默认行为(查询时过滤Schema外的字段),添加以下配置即可消除警告:const mongoose = require('mongoose'); mongoose.set('strictQuery', true); // 执行数据库连接 mongoose.connect('你的MongoDB连接URI') .then(() => console.log('数据库连接成功')) .catch(err => console.error('连接失败:', err));
关键注意点:mongoose.set()的代码必须放在mongoose.connect()之前执行,否则警告无法被正确处理。
内容的提问来源于stack exchange,提问作者Sahil Jain
相关产品推荐
相关产品推荐

