如何修复正在更新与NodeJS中发送的ID不同的ID的PUT路由

时间:2019-01-09 04:23:40

标签: node.js json express nosql postman

PUT路由更新对象的ID错误。

我尝试从params.id更改为body.id,但仍然不会更改输出。它正在更新,但仅更新有史以来创建的第一个与发送的ID不匹配的对象。

app.put('/:id', jsonParser, (req, res) => {
 const requiredFields = ['destination', 'when', 'lastDayOfTrip'];
  for (let i=0; i<requiredFields.length; i++) {
    const field = requiredFields[i];
    if (!(field in req.body)) {
    const message = `Missing \`${field}\` in request body`
    console.error(message);
    return res.status(400).send(message);
    }
 }

    if (req.params.id !== req.body.id) {
     const message = `Request path id (${req.body.id}) and request 
     body id (${req.body.id}) must match`;
     console.error(message);
     return res.status(400).send(message);
     }

 TripPost
 .update({
    id: req.params.id,
    destination: req.body.destination,
    when: req.body.when,
    lastDayOfTrip: req.body.lastDayOfTrip
 })
 .catch( err => res.status(500).json({ message: 'Something went 
  wrong'}));
 console.log(TripPost)
 res.status(204).end();
 }); 

PUT路由应该更新具有匹配ID的对象。相反,仅更新曾经创建的第一个对象,即使不是发送的ID。

2 个答案:

答案 0 :(得分:0)

  Please revise your query, update function require two objects, 
 first object is conditional object and the second object should data to be updated.   
 TripPost
 .update({

    _id: req.params.id,     // Please change id to _id in update query
   },
    {
 $set: {   
    destination: req.body.destination,
    when: req.body.when,
    lastDayOfTrip: req.body.lastDayOfTrip
   }
  }})
 .then(tripData=> {
     console.log(tripData) 
      res.status(200).json({ data: tripData}));
   })
 .catch( err => 
   res.status(500).json({ message: 'Something went wrong'}));
 }); 

答案 1 :(得分:0)

我能够通过以下方式对其进行修复:

 if (!(req.params.id && req.body.id && req.params.id === req.body.id)) {
        res.status(400).json({
          error: 'Request path id and request body id values must match'
        });
    }

    const updated = {};
    const updateableFields = ['destination', 'when', 'lastDayOfTrip', 
    'tripDetails'];
    updateableFields.forEach(field => {
        if (field in req.body) {
          updated[field] = req.body[field];
        }
    });

    TripPost
        .findByIdAndUpdate(req.params.id, { $set: updated }, { new: true })
        .then(TripPost => res.status(204).end())
        .catch(err => res.status(500).json({ message: 'Something went wrong' 
         }));
        res.status(204).end();