0

I'm trying to pull an object from a mongodb array.

Here is my schema,

var VendorSchema = new Schema({

  _id: {
     type: Schema.Types.ObjectId,
     ref: "User"
  },
  service_orders: {
     pending_approval: [{
          service_order: {
              type: Schema.Types.ObjectId,
              ref: "ServiceOrder"
          },
          package: {
              type: Schema.Types.ObjectId,
              ref: "ServicePackage"
          }
     }]
  } 
)}

And my query is,

 var marked_vendors =[ 5a76c4566b0e8c261cc47496, 5b05380f1cab52045c2afc1a ]

 Vendor.update({ '_id': { $in: marked_vendors } }, { $pull: { 'service_orders.pending_approval.service_order': req.body.serviceorder_id } }, { new: true }).exec(function(err, vendors) {
   if (err) {
        console.log(err);
        return res.json({ success: false, msg: err });
   } else {
        return res.json({ success: true, msg: 'Successfully pulled' });
   }
 });

But the problem is, Sometimes 'service_orders.pending_approval' can be an empty array. and it gives me following error

{
    "success": false,
    "msg": {
        "name": "MongoError",
        "message": "Cannot use the part (service_order) of (service_orders.pending_approval.service_order) to traverse the element ({pending_approval: []})",
        "driver": true,
        "index": 0,
        "code": 28,
        "errmsg": "Cannot use the part (service_order) of (service_orders.pending_approval.service_order) to traverse the element ({pending_approval: []})"
    }
}

Its not possible to go with try catch blocks to skip the error. So could anyone please help me on this?

Achira Shamal
  • 527
  • 1
  • 5
  • 18
  • `{ $pull: { "service_orders.pending_approval": { "service_order": req.body.serviceorder_id } } }` Like the error says, "you stepped over the array boundary". You need to stop the key to `$pull` from at the "array" and put the condition ( inner key ) inside the statement which is the "query" to select what to "pull". – Neil Lunn May 26 '18 at 03:45
  • I didn't get what you said, could you please post a sample code. By the way I think this is not a duplicate question – Achira Shamal May 26 '18 at 03:55
  • Please look at the corrected statement and also the same example on the duplicate. The `$pull`operator official documentation also has very similar samples. – Neil Lunn May 26 '18 at 04:01

0 Answers0