2

i am updating 2 documents using mongoose.save(), but i think the way I am doing is is not safe, as far as i know i need to use async to make sure all documents are being executed

// array containing the 2 documents from db 
let schedules 
let newItem = {
   isActive: room.isActive,
   name: room.roomname
};

// adding new items to nested array
schedules[0].rooms.push(newItem);
schedules[1].rooms.push(newItem);

// saving / updating documents 


var total = schedules.length,
  result = [];

function saveAll() {
  var doc = schedules.pop();

  doc.save(function(err, saved) {
    if (err) throw err; //handle error

    result.push(saved);

    if (--total) saveAll();
    else {
      // all saved here
      res.json(result);
    }
  });
}

saveAll();

any explanation how to do it correctly

2 Answers 2

4

We can use promise.all for this but we need to change your save function to promise based function

...

var total = schedules.length,
  result = [];

function saveAll() {
  const promises = schedules.map(schedule => save(schedule));
  return Promise.all(promises)
    .then(responses => {
      // all saved processes are finished
      res.json(responses);
    })
}

// convert callback `save` function to promise based
function save(doc) {
  return new Promise((resolve, reject) => {
    doc.save((err, saved) => {
      if (err) {
        reject(err);
      }

      resolve(saved);
    });
  });
}

If you can use async/await we can make saveAll function cleaner

async function saveAll() {
  const promises = schedules.map(schedule => save(schedule));
  const responses = await Promise.all(promises);

  res.json(responses);    
}

Hope it helps

Sign up to request clarification or add additional context in comments.

1 Comment

it might be a bad idea to use Promise.all( <array of mongo queries> ) because there is a finite pool of connections to mongo (I think default is 5), so this one command could swamp the pool for several hundred milliseconds (or whatever), blocking all other access to mongo from this process.
0

Use Promises :

doc1.save().exec().then(
    data => {

        doc1.save().exec().then(
            data2 => console.log(data2)
        ).catch(err2 => console.log(err2))
    }
).catch(err1 => console.log(err1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.