1

I have a node/express app using mongo.

I have a collection called "paymentMethods", where I store documents that contain the following:

{
   owner_id,
   name_on_card,
   card_number_last_4,
   isActive
}

An owner can have multiple cards in this collection.

When I add a new card, I make the "isActive" true, like so:

router.route('/')
.post(function( req, res ){


  PaymentMethod.findAndUpdate({owner_id:req.body.ownerId})

  var paymentMethod = new PaymentMethod();

    paymentMethod.owner_id = req.body.ownerId;
    paymentMethod.card_number = req.body.cardNumber; 
    paymentMethod.name_on_card = req.body.nameOnCard;
    paymentMethod.exp_date = req.body.expDate;
    paymentMethod.cvv = req.body.cvv;
    paymentMethod.zipcode = req.body.zipCode;
    paymentMethod.active = true;

    console.log('Payment information passed: ', paymentMethod);


    paymentMethod.save(function(err, paymentMethod){
      if(err)
        res.send(err);
      res.json(paymentMethod);
    })

});

What I'm trying to figure out is how I can, in the same call, update all the other matching records and set their "isActive" fields to null or false.

Thanks in advance to the gurus!!

cnak2
  • 1,711
  • 3
  • 28
  • 53
  • I don't think it is possible to do this. You are trying to insert one document and update other documents. That is at least 2 operations no matter what trick you find in mongoose. – Mikey Jul 21 '17 at 18:46
  • Instead of `bool` you "could" use a numeric value. Then you can essentially "toggle" via [`$bit`](https://docs.mongodb.com/manual/reference/operator/update/bit/). But the problem here is the "creation" part, and there is no such operation to actually "create" something new as well as "update other matches" in a single request. You could use [`.bulkWrite()`](http://mongoosejs.com/docs/api.html#model_Model.bulkWrite) which sends "multiple operations" in "one request". Otherwise there is not really another option to two these two different things in a single request. – Neil Lunn Jul 21 '17 at 23:32
  • So there is no way to do this in a single call. I'd have to do a findAndUpdate first and basically set all the isActive fields in each document to null first. Then create the new card. In the case of updating which card should be active, same thing? Am I on the right track? – cnak2 Jul 22 '17 at 01:14

0 Answers0