Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm adding ObjectId to an array from another array that I receive as the body.

exports.updateBasket = function (req, res) {
  Basket.findOne({ _id: req.params.id }, function (err, basket) {
    for(var i=0, len=req.body.length; i < len; i++) {
      basket.update({$addToSet: { "items": req.body[i] } }, { upsert: true, safe: true });
    }
    if (err) {
      res.send(err);
    }
    else {
      res.json({ message: 'Successfully added' });
    }
  });
};

I have 2 questions concerning this :

  1. Is there any upside to do the loop in angular and have multiple PUT?
  2. What is the way to update this same array but when removing ObjectId?

One way that I thought of was to loop ObjectId that have to be removed and look if they are in the array of the object, if yes, delete them.

Another way would be to clear the array when PUT is called and update with the new ObjectId list (which would be the ones that were there minus the one user removed).

Both doesn't feel right ...

thanks

share|improve this question

1 Answer 1

You code looks a bit odd. You are fetching asynchronously on the req.params._id but you are queuing up req.body.length potential worth of updates, but you send 'success' before you even get a response back from the updated results.

If you wanted to filter on arrays, look at lodash, if you want to process multiple updates asynchronously and get those response use async modules.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.