簡體   English   中英

如何在子文檔數組節點貓鼬中推送多個對象

[英]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."
        }
    }

       

我在 createPincode 控制器中哪里出錯了?

請忽略thisdbhjdbbdasjbjsjhhh hddddddddddddddddd djshdsjds jdhsd jsdhfsh fffffffffffffffffffffffffffff fffffffffffffffffffffff fffffffffffffffffffjjjjjjjjjjjjjjjj jjjjjjjjjjjjjjjjjjjj dddddddddddddddddd ffffffffffffffffff gjgjdfsk fdjfdonf fjfdonfdjofd fajdfknadfsofd dafsjdfsonfds dfsjfjdfsoj

您的位置已經是一個數組,並且您正在嘗試將數組推入數組。 而不是僅僅創建位置對象,如

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

並將供應商對象中的此位置推送為

vendor.location.push(location)

這將通過使用 forEach 循環來解決,或者您也可以使用 map

 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");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM