Jenny Mok
Jenny Mok

Reputation: 2804

wait findOneAndUpdate in a loop end

names.forEach((o, i) => {
                Name.findOneAndUpdate({name: o.name}, o, {upsert: true, 'new': true})
                .then(result => {
                    res.json(result);
                })
            })

I cant do res.json in above's loop, how to do handle this case? I want to find name exist or not, if exist don't do anything, otherwise insert the names.

Upvotes: 0

Views: 1739

Answers (2)

Maicon Gilton
Maicon Gilton

Reputation: 691

This works for me

const promises = names.map(async obj => 
   await Name.findOneAndUpdate(
      {name: obj.name}, 
      obj, 
      {upsert: true, 'new': true}
   )
)
await Promise.all(promises)

console.log('test')

if you run this code you will see 'test' only appears after the promises.

Upvotes: 0

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

First of all read this.

What is the difference between synchronous and asynchronous programming (in node.js)

You mixing it up.

To fix your code you can use promises...

For example

function runUpdate(obj) {
   return new Promise((resolve, reject) => {
     //you update code here

    Name.findOneAndUpdate({name: obj.name}, {$setOnInsert: obj}, { upsert: true })
      .then(result => resolve())
      .catch(err => reject(err))
    });
  });
}

Now you can run loop and use promise all

let promiseArr = [];
names.forEach(obj => promiseArr.push(runUpdate(obj)));

Finally

Promise.all(promiseArr)
.then((res) => //res.json here)
.catch(err => //err res here)

About not updating documents on existanse. Check this out. https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#op._S_setOnInsert

Hope this helps.

Upvotes: 3

Related Questions