如果错误是重复键,我想再次调用 post 方法。有什么解决方法吗?Id 是使用 Math.Random() 自动生成的。如果错误是重复键,即 E11000,则应重新执行 post 方法以生成新的 id 并将其存储在数据库中。
const newRequestIndividualRouter = express.Router();
newRequestIndividualRouter.use(bodyParser.json());
newRequestIndividualRouter.route('/')
.post(checkAuth,(req,res,next) => { //POST METHOD
req.body.id = Math.floor(Math.random() * 10000000)+100000; //GENERATING ID
NewRequestIndividual.create(req.body)
.then((request) => {
res.statusCode = 200;
res.setHeader('Content-Type','application/json')
res.json(request);
},(err) => {
if(err.code === 11000) {
**** CALL POST METHOD AGAIN ****
}
next(err)
})
.catch((err) => {
next(err)
});
})