Как обновить данные в стеке MERN - PullRequest
0 голосов
/ 16 октября 2019

Я пытаюсь создать маршрут обновления инвентаризации в стеке MERN. Мой маршрут «Добавить новый элемент» работает отлично, но «маршрут обновления», так как отказался от обновления, может кто-нибудь подскажите, пожалуйста, что я делаю неправильно

//Model

const mongoose= require('mongoose');
const Schema = mongoose.Schema;

//create Schema
const ItemSchema = new Schema({

   name : String,
   description : String,
   price : Number,
   quantity : Number,
   supplier : String,
   taxable : Boolean,

});

module.exports=Inventory=mongoose.model('item',ItemSchema,'inventory');


Routes.js

router.post('/update', (req, res) => {
    // inserting a new inventory
    var _id = req.body._id;
    var inventory = {
      name:req.body.name,
      description:req.body.description,
      price:req.body.price,
      quantity:req.body.quantity,
      supplier:req.body.supplier,
      taxable:req.body.taxable,
    };

    Inventory.findByIdAndUpdate(_id, { $set: inventory }, { new: true }, function (err, inventory) {
      if (err) {
        res.status(500);
        res.send(err);
      } else {
        res.status(200);
        res.send();
      }
    });

  });

UpdateForm.js


class InventoryUpdateForm extends Component {
  constructor(props){
    super(props);
    this.state = {
      _id: this.props.match.params._id,
      name: "",
      description: "",
      price: "",
      quantity: "",
      supplier: "",
      taxable: "",
      loading: true,
      date: moment(new Date()).format("YYYY-MM-DD"),
    };
//some code, basically binding change function with "this"
.........................

//Firstly, I get the entire data for the particular id here

componentWillMount(){
    axios.get("/api/inventory/"+this.state._id)
    .then(
      (res) => {    
        var newState = {
          name: res.data.name,
          description: res.data.department,
          price: res.data.price,
          quantity:res.data.quantity,
          supplier:res.data.supplier,
          taxable:res.data.taxable,

        };
        this.setState( newState );
        this.setState( { loading: false } );
      }, 
      (err) => {
        alert('An error occured! Try refreshing the page.', err);
      }
    );
  }

Здесь я обрабатываю случаи события изменения

handleDatePickerChange(date){
    this.setState({ date: moment(date).format("YYYY-MM-DD") });
  }
  handleNameChange(event){
    this.setState({ name: event.target.value });
  }
  handleDescriptionChange(event){
    this.setState({ description: event.target.value });
  }
  handlePriceChange(event){
    this.setState({ price: event.target.value });
  handleQuantityChange(event){
    this.setState({ quantity: event.target.value });
  }
  handleSupplierChange(event){
    this.setState({ supplier: event.target.value });
  }
  handleTaxableChange(event){
    this.setState({ taxable: event.target.value });
  }

И, наконец, отправляю

submitForm(){
    const { _id, name, description, price, quantity,supplier,taxable} = this.state;
    var inventory = {
      _id, name, description, price, quantity,supplier,taxable 
    };
    axios.post('/update', inventory)
    .then(
      (res) => {
        alert('Updated successfully!');
      },
      (err) => {
        alert('An error occurred! Try submitting the form again.', err);
      }
    );
  }

Данные извлекаются, отображаются иЯ действительно обновляюсь, но когда я пытаюсь сохранить его, я получаю сообщение об ошибке

An error occurred! Try submitting the form again

Как мне решить эту проблему?

1 Ответ

1 голос
/ 16 октября 2019

В axios для отлова ошибок мы добавляем блок catch.

Ваш submitForm должен быть таким, можете ли вы попробовать и прокомментировать, что происходит?

submitForm() {
  const { _id, name, description, price, quantity,supplier,taxable} = this.state;
  var inventory = {
    _id, name, description, price, quantity,supplier,taxable 
  };

  axios.post('/update', inventory)
  .then( res => {
    alert('Updated successfully!');
   }   
  )
  .catch(err => {
    console.log(err.response);
    alert('An error occurred! Try submitting the form again.');
  });
}

Также в findByIdAndUpdate, тамнет необходимости использовать $ set, вы можете просто сделать это так:

 router.post("/update", (req, res) => {
  console.log("req.body", req.body);
  // inserting a new inventory
  var _id = req.body._id;
  var inventory = {
    name: req.body.name,
    description: req.body.description,
    price: req.body.price,
    quantity: req.body.quantity,
    supplier: req.body.supplier,
    taxable: req.body.taxable
  };

  Inventory.findByIdAndUpdate(_id, inventory, { new: true }, function(
    err,
    inventory
  ) {
    if (err) {
      console.log("err", err);
      res.status(500).send(err);
    } else {
      console.log("success");
      res.send(inventory);
    }
  });
});

Также вы можете установить подобное состояние в конструкторе, чтобы соответствовать типам данных в схеме mongoose.

    this.state = {
      _id: this.props.match.params._id,
      name: "",
      description: "",
      price: 0,
      quantity: 0,
      supplier: "",
      taxable: false,
      loading: true,
      date: moment(new Date()).format("YYYY-MM-DD"),
    };

И, наконец, давайте преобразуем нашу цену и количество, добавив плюс.

  handlePriceChange(event){
    this.setState({ price: +event.target.value });

  handleQuantityChange(event){
    this.setState({ quantity: +event.target.value });
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...