首页 > 解决方案 > 处理 CRUD 应用程序中的重复值错误(react-redux + express-mongoose)

问题描述

具有应该是唯一的mongoose架构:carNumber

var Schema = mongoose.Schema({
  createdAt: {
    type: Date,
    default: Date.now
  },
  carNumber: {
    type: String, index: {unique: true, dropDups: true},
  },
  carOwner: String
});

使用express控制器功能数据保存到数据库中:

export const addCar = (req, res) => {
  const newCar = new Car(req.body);
   newCar.save((err, car) => {
    if (err) {
      return res.json({ 'success': false, 'message': 'Some Error' });
    }
     return res.json({ 'success': true, 'message': 'Car '+ car.carNumber +' added successfully', car });   
  }) 
}

Unhandled Rejection (TypeError): Cannot read property 'carNumber' of undefined在尝试添加重复值时返回。为避免错误函数更新为验证undefined值:

export const addCar = (req, res) => {
  const newCar = new Car(req.body);
   newCar.save((err, car) => {
     if (car.carNumber === undefined) {
           return res.json({ 'success': false, '': 'Some Error' });
      }
    else {
        return res.json({ 'success': true, 'message': 'Car '+ car.carNumber +' added successfully', car });   
       }  
  }) 
}

但是Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0response.json().then(error => { ... }前端 redux 操作中有所了解:

export const addNewCar = (car) => {
  console.log(car)
  return (dispatch) => {
    dispatch(addNewCarRequest(car));
    return fetch(apiUrl, {
      method: 'post',
      body: car,
    }).then(response => {
      if (response.ok) {
        response.json().then(data => {
          console.log(data.car);
          dispatch(addNewCarRequestSuccess(data.car, data.message))
        })
      }
      else {
        response.json().then(error => {
          dispatch(addNewCarRequestFailed(error))
        })
      }
    })
  }
}

感觉完全迷失在那里......可能有人陷入同样的​​问题吗?

标签: mongodbreactjsexpressmongoosereact-redux

解决方案


正如评论中提到的,我认为你有.then()你的json()而不是你的fetch(). 你需要一些形状:

export const addNewCar = car => {
  console.log(car);
  return dispatch => {
    dispatch(addNewCarRequest(car));
    return fetch(apiUrl, {
      method: "post",
      body: car
    })
      .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw Error('blah')
        }
      })
      .then(data => {
        console.log(data.car);
        dispatch(addNewCarRequestSuccess(data.car, data.message));
      })
      .catch(error => {
        dispatch(addNewCarRequestFailed(error));        
      });
  };
};

推荐阅读