phemieny7
phemieny7

Reputation: 821

why is mongodb returning success and it not posting value into mongodb array

I am working on sending an array value to an existing table in mongodb using the $push and the res.json returns this

// @route   POST api/addshipment/:unitNo
// @desc    Add shipment for each customer
// @access  Private
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 errshipments = 'This user doesnot have an existing warehouse';
           return res.status(404).json(errshipments);
        }else{
          const newPackages = {
          category: req.body.category,
          quantity: req.body.quantity,
          description: req.body.description,
          trackingno: 1214112,
          length: req.body.length,
          height: req.body.height,
          width: req.body.width,
          weight :  12  
        };
          Shipments.updateOne({_id: req.params.user_id}, {paymentStatus: "incomplete"}, { "$push": { "packages": newPackages}})
          .then(shipments=> res.json(shipments));
        }
      });
    });

here is the res.json that i got

{
  "n": 1,
  "nModified": 0,
  "opTime": {
    "ts": "6739809611714396360",
    "t": 3
  },
  "electionId": "7fffffff0000000000000003",
  "ok": 1,
  "operationTime": "6739809611714396360",
  "$clusterTime": {
    "clusterTime": "6739809611714396360",
    "signature": {
      "hash": "Olz9Fehw4JRj/a4rrLOhCxZIO7E=",
      "keyId": "6719390010044317697"
    }
  }
}

instead of something like this

{
  "paymentStatus": "incomplete",
  "_id": "5d85a4fc8e7efe74e4dee830",
  "warehouseNo": "0001",
  "packages": [{
     "quantity": 12,
     "category" : "Hazardous",
            }],
  "date": "2019-09-23T10:46:23.065Z",
  "__v": 0
}

Upvotes: 1

Views: 216

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

It looks like your find and update query both are incorrect.

It should be this:

Find query

Shipments.findOne({_id: req.params.user_id,paymentStatus: "incomplete"})

update Query

Shipments.updateOne({
    _id: req.params.user_id, 
    paymentStatus: "incomplete"
}, { 
    "$push": { 
        "packages": newPackages
    }
})
.then(shipments=> res.json(shipments));

If you want the updated document at the end of the query, you will need to pass {new : true} as the third argument to the update query

Shipments.updateOne({
    _id: req.params.user_id, 
    paymentStatus: "incomplete"
}, { 
    "$push": { 
        "packages": newPackages
    }
},{new:true})
.then(shipments=> res.json(shipments));

Upvotes: 1

Related Questions