简体   繁体   中英

Express/Mongoose route always updates the same item

Im having a problem where if I try to update or create a new item, it only creates 1 item and then just updates that item no matter what i do, is there anything wrong with this route?

// @route   POST api/item
// @desc    Create/Edit item
// @access  Private
router.post(
  "/",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const itemFields = {};
    const { errors, isValid } = validateItemInput(req.body);

    // Check Validation
    if (!isValid) {
      // If any errors, send 400 with errors object
      return res.status(400).json(errors);
    }

    if (req.body.name) itemFields.name = req.body.name;
    if (req.body.component) itemFields.component = req.body.component;
    if (req.body.parameter) itemFields.parameter = req.body.parameter;
    if (req.body.severity) itemFields.severity = req.body.severity;
    if (req.body.description) itemFields.description = req.body.description;
    if (req.body.recomendation)
      itemFields.recomendation = req.body.recomendation;
    if (req.body.resources) itemFields.resources = req.body.resources;

    Item.findOne({ item: req.params._id }).then(item => {
      if (item) {
        // Update
        Item.findOneAndUpdate(
          { item: req.params._id },
          { $set: itemFields },
          { new: true }
        ).then(item => res.json(item));
      } else {
        // Create
        // Save Item
        new Item(itemFields).save().then(item => res.json(item));
      }
    });
  }
);

you are setting item to req.param.id which sets the content of you new item to older item if you give you older item's id so change it

Item.findOneAndUpdate(
          { item: req.params._id },
          { $set: itemFields },
          { new: true }
        ).then(item => res.json(item));
      } else {
        // Create
        // Save Item
        new Item(itemFields).save().then(item => res.json(item));
      }

Looks like you do not have any param in the route.Inorder to use a param like req.params._id , your route should be defined as

router.post("/:_id",() =>{
//access req.params._id here
res.end() 
});

to pass the value for req.params._id , you have to hit the following POST url yoursite.com/21 , where 21 is the req.params._id

https://expressjs.com/en/api.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM