Harshit Singh
Harshit Singh

Reputation: 27

how can i push multiple objects in subdocument array node mongoose

         //my schema:
                
                const vendorSchema = new mongoose.Schema(
              {
                name: {
                  type: String,
                  trim: true,
                  required: true,
                },
            
                contact: {
                  type: Number,
                  required: true,
                  unique: true,
                },
                city: { type: Array, default: [] },
            
                vendorstatus: { type: String, default: "live" },    
            
                 location: [
                   {
                     pincode: { type: Number, required: true },
                     delivery: { type: Number, required: true },
                     dc: { type: String, default: "low" },
                   },
                 ], 
               
              },
              { timestamps: true }
            );
              //  controller to add vendor:
    
        exports.createVendor = asyncHandler(async (req, res) => {
          const { contact, city, vendorstatus } = req.body;
        
          if (!contact || !city || !vendorstatus) {
            res.status(400);
            throw new Error("include all fields");
          }
        
          const vendor = new Vendor({
            name: req.user.name,
            contact,
            city,
            vendorstatus,
          });
        
          await vendor.save((err, vendor) => {
            if (err) {
              return res
                .status(400)
                .json({ error: "Problem while Saving Vendor" + err });
              
            } else {
              return res.json({ sucess: true, vendor });
            }
          });
              //  controller to add location:
                
                exports.createPincode = asyncHandler(async (req, res) => {
                  const { pincode, delivery, dc } = req.body;
                
                  const vendor = await Vendor.findById(req.params.id); 

         

if (vendor) {
            locations = [{
          pincode: Number(pincode),
          delivery: Number(delivery),
           dc: dc,
           }];
                
                    vendor.location.push(locations);
                
                    vendor.save((err, vendor) => {
                      if (err) {
                        return res
                          .status(400)
                          .json({ error: "Problem while saving locations", err });
                      } else {
                        res.status(201).json({ message: "locations added", vendor });
                      }
                    });
                  } else {
                    res.status(400);
                    throw new Error("Vendor not found");
                  }
                });
            
            
                //in postman i pass this data:
                
                
                { "location": [
                  {
                      "pincode":22222222123,
                      "delivery":300,
                      "dc":"low"
                  },
                   {
                      "pincode":222123,
                      "delivery":300,
                      "dc":"low"
                  },
                   {
                      "pincode":2222123,
                      "delivery":300,
                      "dc":"ow"
                  }
                
                ]
                }
                
                
                
              //  response that i get from postman
                
    {
        "error": "Problem while saving locations",
        "err": {
            "errors": {
                "location.12._id": {
                    "stringValue": "\"[ { pincode: NaN, delivery: NaN, dc: undefined } ]\"",
                    "valueType": "Array",
                    "kind": "ObjectId",
                    "value": [
                        {
                            "pincode": null,
                            "delivery": null
                        }
                    ],
                    "path": "_id",
                    "reason": {},
                    "name": "CastError",
                    "message": "Cast to ObjectId failed for value \"[ { pincode: NaN, delivery: NaN, dc: undefined } ]\" (type Array) at path \"_id\""
                },
                "location.12.delivery": {
                    "name": "ValidatorError",
                    "message": "Path `delivery` is required.",
                    "properties": {
                        "message": "Path `delivery` is required.",
                        "type": "required",
                        "path": "delivery"
                    },
                    "kind": "required",
                    "path": "delivery"
                },
                "location.12.pincode": {
                    "name": "ValidatorError",
                    "message": "Path `pincode` is required.",
                    "properties": {
                        "message": "Path `pincode` is required.",
                        "type": "required",
                        "path": "pincode"
                    },
                    "kind": "required",
                    "path": "pincode"
                }
            },
            "_message": "Vendor validation failed",
            "name": "ValidationError",
            "message": "Vendor validation failed: location.12._id: Cast to ObjectId failed for value \"[ { pincode: NaN, delivery: NaN, dc: undefined } ]\" (type Array) at path \"_id\", location.12.delivery: Path `delivery` is required., location.12.pincode: Path `pincode` is required."
        }
    }

       

Where did i go wrong in createPincode controller?

please ignore thisdbhjdbbdasjbjsjhhh hddddddddddddddddd djshdsjds jdhsd jsdhfsh fffffffffffffffffffffffffffff fffffffffffffffffffffff fffffffffffffffffffjjjjjjjjjjjjjjjj jjjjjjjjjjjjjjjjjjjj dddddddddddddddddd ffffffffffffffffff gjgjdfsk fdjfdonf fjfdonfdjofd fajdfknadfsofd dafsjdfsonfds dfsjfjdfsoj

Upvotes: 1

Views: 652

Answers (2)

Harshit Singh
Harshit Singh

Reputation: 27

this will be solved by using forEach loop or you can use map as well

 const vendor = await Vendor.findById(req.params.id);
    const locations = req.body;

    if (vendor) {
      locations.forEach((items) => vendor.location.push(items));

      await vendor.save((err, vendor) => {
        if (err) {
          return res
            .status(400)
            .json({ error: "Problem while saving locations", err });
        } else {
          res.status(201).json({ message: "locations added", vendor });
        }
      });
    } else {
      res.status(400);
      throw new Error("Vendor not found");
    }

Upvotes: 0

Ujjwal Nepal
Ujjwal Nepal

Reputation: 546

Your location is already an array and you are trying to push array into array. Rather than that just create location object like

var location = {
      pincode: Number(pincode),
      delivery: Number(delivery),
      dc: dc,
     }

and push this location in the vendor object as

vendor.location.push(location)

Upvotes: 1

Related Questions