防止CRUD应用程序中的重复值

时间:2018-04-27 11:28:24

标签: javascript reactjs express react-redux crud

有一个简单的CRUD应用程序(BE express和FE react-redux),其中表单值被添加到mongodb,下面的模式:

import mongoose from 'mongoose';

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

export default mongoose.model('Car', Schema);

index: { unique: true }阻止通过error

添加相同的carNumber

使用carActions.js中的调度程序功能选择汽车:

//Async action
export const fetchCars = () => {
  // Returns a dispatcher function
  // that dispatches an action at later time
  return (dispatch) => {
    dispatch(fetchCarsRequest());
    // Returns a promise
    return fetch(apiUrl)
      .then(response => {
        if (response.ok) {
          response.json().then(data => {
            dispatch(fetchCarsSuccess(data.cars, data.message));
          })
        }
        else {
          response.json().then(error => {
            dispatch(fetchCarsFailed(error));
          })
        }
      })
  }
}

并在Cars组件中呈现:

render() {
    const carState = this.props.mappedCarState;
    const cars = carState.cars;
return (

<tbody>
      {cars.map((car, i) => <tr key={i}>
         <td>{car.carNumber} {car.carOwner}</td>
         <td><Button onClick={() => this.deleteCar(car)} ></Button></td>         
   </tr>)
</tbody>
}

我对这种接线很新闻,可能有人建议我应该如何防止错误并返回通知?

我可能会错过一些重要信息,这里是link代表。

2 个答案:

答案 0 :(得分:0)

您应该考虑索引carNumber,以确保MongoDB可以防止字段中的重复值。

for controller in self.navigationController!.viewControllers as Array {
    if controller.isKind(of: SOListScreen .self) {
        self.navigationController!.popToViewController(controller, animated: true)
        break
    }
}

答案 1 :(得分:0)

您应该在架构中为func getPreviousHistory() { DispatchQueue.main.async { let url = ServiceUrl.userOrder var previousOrderArray = [[:]] let params1: [String : String] = [ "userid" : UserDefaults.standard.string(forKey: "userid")! ] print(params1) Alamofire.request(url, method: .post, parameters: params1).responseJSON() { response in switch response.result { case .success: if let data = response.result.value { if (data as? [String : AnyObject]) != nil{ if let dictionaryArray = data as? Dictionary<String, AnyObject> { previousOrderArray = dictionaryArray["data"] as! Array<Dictionary<String, AnyObject>> self.sortedOrdersDictionary = self.sortArrayDictDescending(dict: previousOrderArray as! Array<Dictionary<String, AnyObject>>, dateFormat: "yyyy-MM-dd'T'HH:mm:ss") DispatchQueue.main.async( execute: { self.tableView.reloadData() }) } } } case .failure(let error): print("RESPONSE ERROR: \(error)") if let err = error as? URLError, err.code == URLError.Code.notConnectedToInternet { DispatchQueue.main.async { popupConstants.sharedInstance.showAlert(title: "ALERT", message: "Please check your Internet connection",view: self) } } else { DispatchQueue.main.async { popupConstants.sharedInstance.showAlert(title: "ALERT", message: "An Error Occured",view: self) } } } } } }` 创建unique索引。

这将确保在carNumber

的集合中不添加重复值
carNumber