0
router.post(
  '/addshipment/:user_id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {

    Shipments.findOne({_id: req.params.user_id}, {paymentStatus: "incomplete"})
      .then(shipments => {
        if(!shipments){
          const errwarehouse = 'This user doesn't have a warehouse, kindly create that first'
          return res.status(404).json(errwarehouse);
        }else{
        const newPackages = {
          category: req.body.category,
          quantity: req.body.quantity,
          description: req.body.description,
          trackingno: 1234321,
          length: req.body.length,
          height: req.body.height,
          width: req.body.width,
          weight :  12  
        };


        shipments.packages.push(newPackages);
        shipments
              .save()
              .then(shipments => res.json(shipments))
              .catch(err => console.log(err));
      }

  });
});

i don't know why i do get this error,

"TypeError: Cannot read property 'push' of undefined"

because all am trying to acheive is to make sure i am able post post into the package array

phemieny7
  • 803
  • 7
  • 21
  • I suggest learning the atomic operators such as [`$push`](https://docs.mongodb.com/manual/reference/operator/update/push/). Generally using a `find/modify/save` pattern is a really bad practice which atomic operations avoid. Also there is a general failing in your logic since the attempt to `shipments.packages.push` actually happens *outside* of the block in which you checked if `shipments` was even defined ( i.e "found" ), and hence the error here. But the atomic `$push` does not have this problem. – Neil Lunn Sep 22 '19 at 10:39
  • @NeilLunn please can you help me with it, all those codes i saw ain't working for me – phemieny7 Sep 22 '19 at 20:34

0 Answers0