如何将多个req.body.data插入对象数组的子文档中?

时间:2019-07-15 08:52:11

标签: node.js api mongoose

我在将多个用户输入插入到对象Farm数组中时遇到麻烦。我将Farm添加到用户中的api无法正常工作。我不知道我的代码有什么问题。请帮忙。我正在请求api调用。

我尝试将手动输入代码成功地插入数据到mongodb 喜欢

//addDevice
router.post("/addDevice/:id",(req,res) =>{
  req.body={modelNumber:"xxx-xxx-sp01",deviceType:"Rasberry",description:"Just testing Manual Data input from Request Body",deviceLocaion:"12.30"};
  User.findByIdAndUpdate(req.params.id,
    {$push:{"farm.0.device":req.body},
    $currentDate:{lastModified:true,"deviceModifyDate":{$type:"timestamp"}}},
    {safe:true,upsert:true,multi:false,new:true},
        function(err,User){
    if(err)
  {
    console.log(err);
    return res.send(err);
  }
  return res.status(200).json(User);
  });
});

但是我希望插入的用户数据不是硬编码的。我尝试这样做,但是没有用。

   // Form validation done
   // adding of farms on any user
   //addFarm
router.post("/addFarm/:id",(req,res) => {
const { errors, isValid } = validatelocationDeviceInput(req.body);
  // Check validation
  if (!isValid) {
    return res.status(400).json(errors);
  }
   //farmLocation:req.body.farmLocation;
   //description:req.body.description;
  var farm={farmLocation:req.body.farmLocation,description:req.body.description}
  User.findByIdAndUpdate(req.params.id,
  {$push:{"farm":farm},$currentDate:{lastModified:true,"farmModifyDate":
  {$type:"timestamp"}}},
  {safe:true,upsert:true,multi:true,new:true},
  function(err,User){
  if(err){
    console.log(err);
    return res.send(err);
  }
  return res.status(200).json(User);
  });
});

// User Schema
const UserSchema = new Schema({


  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true
  },
  location:{
      type:String,
      required:true,

  },

  createdDate: {
    type: Date,
    default: Date.now
  },

  farm:[
      {
        farmLocation:String,
        description:String,
        farmAddDate:{type:Date,default:Date.now},
        device:[{Device}]
     },

 ],


},
{strict:false}
);

Error:404:Cannot POST /api/addFarm/5d29cbf912af904d7cd70670

0 个答案:

没有答案