Tuesday 21 August 2018

Wait for mongoose save() before continuing

Hi, I have the following piece of code:commentsAuthors.forEach((commentAuthor) => { //some code saveUsersPromises.push(User.findOne({_id: commentAuthor.id}).then((commentAuthor1) => { commentAuthor1.comments.splice(position, 1); commentAuthor1.save().catch((err) => {console.log(err)}); })) }) Promise.all(saveUsersPromises) So basically i have an arrray of documents retrieved from my DB. I run a forEach over this array and each time i perform some operations, and then refresh (re-fetch) the current document, change it and then save it. The problem occurs when i have 2 documents that are the same. For the first it works fine but saving the second one throws a version error. I think this happens because the second document is retrived (line 3) before the previous one is saved (therefore its version isn't changed). How can i wait for the document to save before retriving another one? Is there a better solution?Thanks in advance ;)

Submitted August 21, 2018 at 08:05AM by everek123

No comments:

Post a Comment