Mongoose中find()方法报错:不再支持回调函数,求解决方案
解决MongooseError: Model.find() no longer accepts a callback问题
Mongoose 6及以上版本彻底移除了find()等查询方法的回调参数支持,必须改用Promise风格的写法,以下是两种可行的解决方案:
1. 使用async/await(推荐)
这是最简洁易读的写法,需要在异步函数中使用:
// 假设你的数据模型是User async function fetchUsers() { try { // 执行查询,无查询条件则传空对象{} const users = await User.find({}); // 处理查询到的结果 console.log(users); } catch (error) { // 捕获并处理错误 console.error('查询失败:', error); } } // 调用函数 fetchUsers();
如果是在Express路由中使用,直接将路由处理函数声明为async即可:
app.get('/api/users', async (req, res) => { try { const users = await User.find({}); res.status(200).json(users); } catch (error) { res.status(500).json({ message: '查询用户失败', error: error.message }); } });
2. 使用Promise.then()链式调用
如果你习惯Promise的链式写法,也可以这样实现:
// 执行查询 User.find({}) .then(users => { // 处理结果 console.log(users); }) .catch(error => { // 处理错误 console.error('查询失败:', error); });
内容的提问来源于stack exchange,提问作者anas
相关产品推荐
相关产品推荐

