MongooseError:Model.create() 不再接受回调

1 mongoose node.js

M_User\n  .create(data, (err) => {\n      if (err) res.send({\n          kq: 0,\n          msg: 'k\xe1\xba\xbft n\xe1\xbb\x91i DB th\xe1\xba\xa5t b\xe1\xba\xa1i'\n        })\n     res.send({\n          kq: 1,\n          msg: '\xc4\x90\xc3\xa3 th\xc3\xaam th\xc3\xa0nh c\xc3\xb4ng'\n       })\n})   \n
Run Code Online (Sandbox Code Playgroud)\n

错误如下:

\n
throw new MongooseError('Model.create() no longer accepts a callback');\n      ^\nMongooseError: Model.create() no longer accepts a callback\nat Function.create (C:\\Users\\ASUS\\OneDrive\\M\xc3\xa1y t\xc3\xadnh\\project-17-12\\node_modules\\mongoose\\lib\\model.js:2772:11)\nat C:\\Users\\ASUS\\OneDrive\\M\xc3\xa1y t\xc3\xadnh\\project-17-12\\router\\R_User.js:101:18\nat process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n
Run Code Online (Sandbox Code Playgroud)\n

这就是我曾经使用过的方法,使用 Express.js 和 Mongoose。

\n

我该如何修复它?

\n

小智 5

从版本 6.0.0 开始,Mongoose 中的方法不再接受回调作为最后一个参数。相反,它返回一个承诺。您应该更新代码以使用 Promise 来处理 create() 方法的结果

\n
M_User.create(data)\n.then((result) => {\n  res.send({ kq: 1, msg: '\xc4\x90\xc3\xa3 th\xc3\xaam th\xc3\xa0nh c\xc3\xb4ng' })\n})\n.catch((err) => {\n  res.send({ kq: 0, msg: 'k\xe1\xba\xbft n\xe1\xbb\x91i DB th\xe1\xba\xa5t b\xe1\xba\xa1i' })\n})\n
Run Code Online (Sandbox Code Playgroud)\n