Express and Mongoose fail to handle multiple requests at same time

社会主义新天地 提交于 2020-01-06 06:28:30

问题


So I have an API call /add which will add a car into my intersection when POST to it. So currently I'm writing a batch to add multiple cars at a short time by calling curl command in the background with & in UNIX shell. According to my log, all requests (total 125) has successfully sent to the server and the server has received it properly. But no matter how many time I try the intersection won't have a total of 125 cars, sometimes it'll have around 80, sometimes I only get like 40.

I'll probably guess that it's mongoose who make this error. I guess that it might be that while one request is adding the car to MongoDB another request came in, so probably because of that, the second request's car isn't added into the database.

Following is a part of my code. I'm trying to find a way so that all my cars (requests) are added into the database properly.

db.car.create({
    license: license,
    type: "small",
    speed: 60
}, (rtd) => {
    var id = rtd._id;
    db.scene.add(nowCIns, req.body.position, req.body.direction, id, (rtd2) => {
        res.json(rtd2);
    })
})
//db.js
car: {
    create: (obj, cb) => {
        cb = cb || function (cbr) { };
        car.create(obj, (err, res) => cb(res.toObject()));
    },
    modify: (obj, cb) => {
        cb = cb || function (cbr) { };
        car.updateOne({ _id: obj._id }, obj, (err, res) => cb(res));
    },
    get: (id, cb) => {
        cb = cb || function (cbr) { };
        car.findOne({ _id: id }).lean().exec((err, res) => {
            cb(res);
        })
    },
    getAll: (cb) => {
        cb = cb || function (cbr) { };
        car.find({}).lean().exec((err, res) => {
            cb(res);
        })
    }
}

来源:https://stackoverflow.com/questions/55661888/express-and-mongoose-fail-to-handle-multiple-requests-at-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!