Mongoose报错:Model.find()不再支持回调函数,求解决方案
解决Mongoose报错:Model.find() no longer accepts a callback
新版本Mongoose已废弃Model.find()方法的回调参数,所有查询方法现在默认返回Promise,需改用Promise语法或async/await改写代码,以下是两种可行方案:
方案1:使用async/await(推荐)
将查询逻辑封装在async函数中,通过try/catch捕获错误:
async function getFruits() { try { const fruits = await Fruit.find(); console.log(fruits); } catch (err) { console.log(err); } } getFruits();
如果是在Express路由等场景下,直接将路由处理函数声明为async即可:
app.get('/fruits', async (req, res) => { try { const fruits = await Fruit.find(); res.send(fruits); } catch (err) { res.status(500).send(err); } });
方案2:使用Promise链式调用
利用Mongoose查询方法返回的Promise,通过.then()处理成功结果,.catch()捕获错误:
Fruit.find() .then(fruits => { console.log(fruits); }) .catch(err => { console.log(err); });
内容的提问来源于stack exchange,提问作者Nitesh Kohli
相关产品推荐
相关产品推荐

