How to manage concurrency in MongoDB and auto Increment in the same time

Viewed 201

I have a specific requirements where customer has asked that they wand id to be auto increment with number. And still can manage to deal with concurrent when it's happened.

The logic is first check is: 1. Check if user is allow with write permission 2. check if the req.body has sufficient information 3. Check if the collection already has data or not 4. if collection has data auto increment the tugboatId or set tugboatId to 1

Here is my code:

interface ITugBoatBase {
  name: string
}

interface IResponseMessage {
  status: number;
  message: string
}

type InputC = ITugBoatBase ;
type OutputC = IResponseMessage

public async CreateTugBoat (data: ITugBoatBase): Promise<IResponseMessage> {
  let _input: InputC[] = data.parameters['reqParameters'];
  let _reqParameter: InputC = data.parameters['reqParameter'];
  let _reqIndex: number = data.parameters['reqIndex'];
  let _resMessage: IResponseMessage = data.parameters['resMessage'];

  try {
    let _userInfo = await Db.GetUserInfo(data.request, data.user);
    if (!_userInfo) {
      throw Errors.throw(Errors.CustomBadRequest, ['TugBoat Process Required login or Register first']);
    }

     // validation req.body
     try {
       await IDB.TugBoatInfo.Validate(_reqParameter);
     } catch (error) {
       throw Errors.throw(Errors.CustomBadRequest, [error]);
     }

     let db = await sharedMongoDB();
     let collectionName: string = IDB.TugBoatInfo.name;
     let collection: Collection<Model.MongoData<IDB.ITugBoatInfo>> = db.collection(collectionName);

     let res = await collection.insertOne(
       {
          tugboatId: (await collection.find().count()) + 1,
          name: _reqParameter.name,
          portEngineHrs: 0,
          startBoardEngineHrs: 0,
          generatorRunningHrs: 0,
       },
       (err, res) => {
          return new Promise((resolve, reject) => {
               if (err) reject(err.message);
               resolve(res);
          });
       },
     );

     return {

        statusCode: 200,
        message: ''
     }
  } catch (e) {
    throw new Error(e);
  }
}

After complete the code i use postman for testing with the data as following

Request

{
    "sessionId": "{{sessionId}}",
    "datas": [
        {
            "name": "test1"
        },
        {
            "name": "test2"
        }
    ]
}

I expexted the result should be test1 create first with tugboatId set as 1, then test2 creat with tugboadId auto increment to 2.

However, the outcome is both datas tugboatId are the same not auto incremented

Result

[
  {
    _id: ObjectId("5ec65fc2a3d2d12a7c8b20df"),
    tugboatId: 1,
    name: test2,
    portEngineHrs: 0,
    startBoardEngineHrs: 0,
    generatorRunningHrs: 0
  },
  {
    _id: ObjectId("5ec65fc2a3d2d12a7c8b20e0"),
    tugboatId: 1,
    name: test1,
    portEngineHrs: 0,
    startBoardEngineHrs: 0,
    generatorRunningHrs: 0
  }
]

Not sure why it goes wrong

0 Answers
Related