我正在使用mongoose js,并尝试将新文档插入mongodb。我正在传递数据对象以使用Axios进行表达。当我收到验证错误时,快递服务器非常容易地识别问题。它返回错误productCode: ValidatorError: Path 'productCode' is required.
返回表示的错误是一个巨大的对象,我在其中找不到验证错误。有人可以告诉我我的捕获错误中缺少什么吗?
已更新
路径:Express axios Post catch error
const product = {
productCode: '1a',
productName: 'product x'
};
async function createProduct(product) {
axios
.post(
`http://localhost:3000/myroute`,
product
)
.then((res) => {
console.log('res', res.data.productCode);
return res.data.productCode;
})
.catch((error) => {
// console.log('err', err.response);
if (error.response) {
/*
* The request was made and the server responded with a
* status code that falls out of the range of 2xx
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received, `error.request`
* is an instance of XMLHttpRequest in the browser and an instance
* of http.ClientRequest in Node.js
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
// console.log(error);
});
}
更新
路径:Server
const product = new Product(req.body);
product
.save()
.then((result) => {
res.status(200).json(result);
})
.catch((err) => {
console.log('err', err);
res.status(500).json({ error: err.reason });
});
路径:Model
var productSchema = new Schema(
{
productCode: {
type: String,
required: true
},
productName: { type: String, default: '' }
},
{ collection: 'products', timestamps: true, versionKey: false }
);