Mongoose 6.0调用find方法报错cursor.toArray is not a function求助
问题原因
- Mongoose 6.x 底层依赖的MongoDB Node.js驱动4.x对
collection.find()的传参规则做了调整:该方法最多接受2个参数,第一个为查询条件对象,第二个为配置项,不再支持直接传入回调函数作为参数。 - 你当前的写法是直接将回调函数作为
Fruit.find()的唯一参数,不符合新的传参规则,导致底层调用原生方法时参数校验失败,抛出参数错误,后续的cursor.toArray调用也随之报错。
解决方案
方案1:使用exec方法传入回调(适配原有回调写法习惯)
将find方法的查询条件补全为第一个参数,回调函数放到exec()中传入:
// {} 表示查询所有符合条件的文档,不可省略 Fruit.find({}).exec(function(err, fruits){ if(err){ console.log("There was an error"); console.log(err); }else{ console.log(fruits); // 数据处理完成后可按需关闭数据库连接 // mongoose.connection.close() } });
方案2:使用Promise的then/catch写法
Fruit.find({}) .then(fruits => { console.log(fruits) }) .catch(err => { console.log("There was an error"); console.log(err); })
方案3:使用async/await写法(推荐,可读性更高)
// 异步查询逻辑需要放在async标记的函数内 const getAllFruits = async () => { try { const fruits = await Fruit.find({}) console.log(fruits) } catch (err) { console.log("There was an error"); console.log(err); } } // 调用执行查询函数 getAllFruits()
额外优化建议
mongoose.connect是异步操作,建议等待数据库连接成功后再执行查询逻辑,避免偶发的连接未就绪错误:
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true}) .then(() => { console.log("数据库连接成功") // 连接成功后再执行查询操作 // 此处放入上面的查询代码 }) .catch(err => console.log("数据库连接失败:", err))
内容的提问来源于stack exchange,提问作者Something Nice
相关产品推荐
相关产品推荐

