使用Mongoose的find()方法查询数据报错,正确用法是什么?
问题根因
你遇到的两个报错均是Mongoose版本与底层MongoDB Node.js驱动版本不兼容导致的,Full Stack Open 2021课程示例适配的是Mongoose 5.x版本,你大概率安装了Mongoose 6.x/7.x等高版本,新旧版本API存在不兼容差异。另外你第二段查询代码还存在异步逻辑顺序错误。
解决步骤
- 卸载当前版本Mongoose,安装课程适配的稳定版本
npm uninstall mongoose && npm install mongoose@5.13.15
该版本是2021版课程官方测试通过的版本,不会出现上述API不兼容报错。
- 修正查询代码的异步逻辑错误
你写的mongoose.connection.close()是同步执行的,会在find的异步回调执行完成前就关闭数据库连接,导致查询结果返回undefined,需要把关闭连接的逻辑放到回调内部:
// 回调写法 Note.find({}, function (err, docs) { if (err) console.error(err) console.log(docs) mongoose.connection.close() }) // Promise写法 Note.find({}).then(result => { result.forEach(note => console.log(note)) mongoose.connection.close() }).catch(err => console.error(err))
- 若仍有报错,清除依赖缓存后重新安装
rm -rf node_modules package-lock.json npm install
报错说明
TypeError: cursor.toArray is not a function:高版本Mongoose调用了新版MongoDB驱动才有的API,和你本地安装的驱动版本不匹配,对应API不存在。MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments:高版本Mongoose封装find方法时,给底层MongoDB驱动传递了超过2个参数,不符合你本地驱动版本的参数要求。
内容的提问来源于stack exchange,提问作者Pedro Papel
相关产品推荐
相关产品推荐

