mongodb - 处理 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 0
在response.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))
})
}
})
}
}
感觉完全迷失在那里......可能有人陷入同样的问题吗?
解决方案
正如评论中提到的,我认为你有.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));
});
};
};
推荐阅读
- python - 截图 element 的所有子元素
- java - 当具有多个路径段时,引导组件未在 Thymeleaf 模板中呈现
- python - 是否有更有效或更简洁的方法来根据索引列表划分 df?
- java - 如何通过spring cloud stream binder kafka流依赖使用协议缓冲区(protobuf)使用来自kafka主题的消息?
- zsh - 我在 zparseopts 中发现了一个错误还是我做错了
- awk - 使用多个多字符分隔符时替换单个字段中的字符
- laravel - 通知,获取“喜欢”推文的用户
- oracle - 计算工资期结束时的年龄
- arrays - 如何使用 ndarray 从向量向量创建二维数组?
- html - 从 Angular 的文本框中添加/删除值