Foreach with Promise and findAndCreate


#1

Hi everyone,

I am trying to use an async foreach so basic I do this:

each(parsedFile, (fileElement) => {
      promises.push(this.processFileElement(fileElement));
 });
await Promise.all(promises);

So inside processFileElement I have to check if this element exists inside the database if not have to insert this. So I use findOrCreate.

let dbDebtor = await Debtor.findOrCreate(
  { document: xxxxx },
  { document: xxxxx}
)

The problem is findOrCreate it is on two steps the first make a find and after an insert.
And using this inside a promise.all the problem is more than one process do a find inside the database and return that is not register and the both try to insert so, in this case, the database will put in a queue, so the first inside works fine but the second trow an error for a duplicated field.

Have any way to deal with this?

Thanks


#2

Hey @thiagoarioli! :wave:

I didn’t really get your issue.

So you have an array of promises (findOrCreate) and the issue is that sometimes it tries to insert twice the same record?

If it’s the case, it means you have duplicates and need to clean the data you use before.


#3

Yeap the probleman is I was ussing pormises só I need to check and remove all duplicates before run the promises to insert.
Thanks