nodejs mongodb数据库使用mongoose报错Model.find() no longer accepts a callback

文章介绍了Mongoose7.x版本中find()和save()等函数不再接受回调,推荐使用async/await或promises处理。若不想改变,可将Mongoose降级到6.10.0版本以继续使用回调函数。示例代码展示了如何在新版本中正确处理这些操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

翻译一下,mongoose新版7.x废弃了find()\save()方法回调,可以修改为try catch,代码示例如下。

但最简单的就是把mongoose降低到6.10版本就可以了
npm uninstall mongoose
安装
npm install mongoose@6.10.0
完事。

 

Use async/await or promises for Mongoose functions

As Mongoose Released Version 7.x They Deprecated Some Functions As Per Official Documents functions no longer accept callbacks. They always return promises. To Solve MongooseError: Model.find() no longer accepts a callback error You need to Use async/await or promises for Mongoose functions. As Like Given below.

app.get("/posts", async (req, res) => {

  try {
    const posts= await Posts.find({ });
    res.send(posts);
    console.log(posts);
  } catch (err) {
    console.log(err);
  }

});

Or You are Using Save Function then You Need to Use the async function. As I Have Given Below.

// You need to use Async Function
const result = await data.save()
console.log(result);

And Now, Your error will be Solved.

Downgrade mongoose To 6.x

If You do not want to change the Function callback then You can Downgrade Your mongoose to Version 6.x. First of all, uninstall mongoose By running the npm command.

npm uninstall mongoose

And now, You need to install mongoose 6.x.

npm install mongoose@6.10.0

And now You can use the callback function without facing any error.










参考MongooseError: Model.find() no longer accepts a callback - Pincods.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值