0

如果错误是重复键,我想再次调用 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)
    });
})
4

2 回答 2

0

Math.random() 根据当前时间自动播种

你需要一个好的伪随机数生成器

试试http://davidbau.com/seedrandom

于 2020-07-30T04:31:04.297 回答
0

您可以使用 uuid 代替 Math.random()。链接 - https://www.npmjs.com/package/uuid

于 2020-07-30T04:46:48.823 回答