Start a new topic

Lock a field in a collection

Hi guys,


Perhaps this is sound silly as I understand that there is no transactional  for nosql database. However, if someone can provide a workable solution that would be very helpful.


My client need a running id number for each bag of their production output. it is like


bag 1 : B00001

bag 2 : B00002

bag 3 : B00003

bag 4 : B00004


and etc


and I will create a collection just to maintain the running number. A few people may update the running number at the same time so it need to be locked then release.


Appreciate any workaround solution please. Thanks !


Cheers,

Mark Thien



 

1 Comment

Mark, you can do this fairly easily using CollectionAccess and collection hook.   In general you would just need 1 field with a number, then simply increment it.


A code like this might do the trick:


function onPreSave(request, response, modules){

    var info = modules.logger.info;

    var collectionAccess = modules.collectionAccess;

    collectionAccess.collection('Counter').findAndModify({"Counter": {$exists:true}},{}, {$inc: {'Counter': 1}},{new: true},

   

  function(err, doc) {

   if (err) {

     return response.error(err);

   } else if (!doc.Counter) {

     return response.error("Counter does not exist");

   }

   request.body._id = doc.Counter+'';

   response.continue();

  });

}


1 person likes this
Login or Signup to post a comment