Mongoose异步函数内调用find()方法运行报错无法获取数据如何解决?
Mongoose调用find()查询集合文档报错解决方案
报错根因
你遇到的MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments报错,是当前安装的mongoose版本与其依赖的MongoDB Node.js驱动版本不兼容导致,该问题常出现在mongoose 5.x版本搭配过高版本驱动的场景。
解决步骤
- 第一步:卸载当前已安装的mongoose包
执行命令:npm uninstall mongoose - 第二步:安装匹配度稳定的6.x版本mongoose
执行命令:npm install mongoose@6.x - 第三步:优化异步查询的错误捕获逻辑,避免未处理的Promise rejection警告,修改
getDocument方法如下:
const getDocument = async () => { try { const result = await Playlist.find() console.log(result); } catch (err) { console.error('查询失败:', err) } }
修改完成后重新执行node src/app.js即可正常输出集合内的所有文档。
内容的提问来源于stack exchange,提问作者Mohit Ashliya
相关产品推荐
相关产品推荐

