0
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.

Jenny Mok
  • 2,744
  • 9
  • 27
  • 58
  • You can use [async.map()](https://caolan.github.io/async/docs.html#map) but ensure you execute `findOneAndUpdate` using a callback instead of returning a Promise. – Mikey Nov 11 '17 at 13:53

2 Answers2

3

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.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24
0

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.

Maicon Gilton
  • 581
  • 1
  • 7
  • 6