0

So here's a problem which i am facing when i am using the post init hook whenever the date changes i update some values in the db. but when i am trying to make a get call the parallel save error comes up, but the values in database get updated and if i try to hit api again it works perfectly fine, so why do i get this parallel save error just once and not again until the date changes again.

influencerSchema.post('init', async function (doc) {
  let metaData = influencerModel.metaData();
  let refreshFields = metaData.refreshFields;
  for (let i = 0; i < refreshFields.length; i++) {
    if (new Date(doc.currentMembership[refreshFields[i]].dailyCount.date).setHours(0, 0, 0, 0) != new Date().setHours(0, 0, 0, 0)) {
      doc.currentMembership[refreshFields[i]].dailyCount.date = Date.now();
      doc.currentMembership[refreshFields[i]].dailyCount.count = doc.currentMembership[refreshFields[i]].count;
      await doc.save();
    }
  }
});

here refresh fields are

refreshFields: ['likes', 'messages', 'matches', 'backtrack']

any help would be great Thanks!

1 Answers1

0

I don't know why you are trying to save the doc multiple times in a init hook in the first place. AFAIK this is not necessary. I would drop the line await doc.save(); entirely (and make the function non-async). Should be OK if you save the doc later anyway.

The error occurs exactly for the reason the error message is stating: You are trying to save the document muliple times in parallel.

Checkout https://mongoosejs.com/docs/middleware.html#post-async
You are not using the async function schema because you are required to call next() when you are done with your async processing.

So either don't save the doc in the hook or use the next() callback when done with async stuff.

alexloehr
  • 1,773
  • 1
  • 20
  • 18