将对象数组从 React 推送到 mongodb+express 服务器问题
Pushing Array of object from react to mongodb+express server issue
我正在存储对象数组,但它给了我以下错误。
(node:87929) UnhandledPromiseRejectionWarning: ValidationError: Place validation failed: placesToVisit: Cast to embedded failed for value "[{"name":"xczc","location":"zczxc","description":"由于“ObjectParameterError”
,路径“placesToVisit”处的 czxczx“}]”(类型字符串)
这是我的架构:
placesToVisit: [
{
name: {
type: String,
required: [true, "Please enter the place's name"],
},
description:{
type: String,
required: [true, "Please enter the place's description"],
},
location:{
type: String,
required: [true, "Please enter the place's location"],
}
},
],
这是我的控制器:
exports.createPlace = async (req, res) => {
try {
const newPlace = await new Place({
placesToVisit:req.body.placesToVisit,
});
newPlace.save()
debugger
res.status(201).json({
success:true,
message:"Place Created Successfully",
newPlace
})
} catch (error) {
return res.status(500).json({
success:false,
error:error.message
})
}
};
这是我的表单数据结构:
data.append("placesToVisit",JSON.stringify(values.placesToVisit))
这是yaload的ss
您必须将字符串转换为数组:
placesToVisit: JSON.parse(req.body.placesToVisit),
我正在存储对象数组,但它给了我以下错误。
(node:87929) UnhandledPromiseRejectionWarning: ValidationError: Place validation failed: placesToVisit: Cast to embedded failed for value "[{"name":"xczc","location":"zczxc","description":"由于“ObjectParameterError”
,路径“placesToVisit”处的 czxczx“}]”(类型字符串)这是我的架构:
placesToVisit: [
{
name: {
type: String,
required: [true, "Please enter the place's name"],
},
description:{
type: String,
required: [true, "Please enter the place's description"],
},
location:{
type: String,
required: [true, "Please enter the place's location"],
}
},
],
这是我的控制器:
exports.createPlace = async (req, res) => {
try {
const newPlace = await new Place({
placesToVisit:req.body.placesToVisit,
});
newPlace.save()
debugger
res.status(201).json({
success:true,
message:"Place Created Successfully",
newPlace
})
} catch (error) {
return res.status(500).json({
success:false,
error:error.message
})
}
};
这是我的表单数据结构:
data.append("placesToVisit",JSON.stringify(values.placesToVisit))
这是yaload的ss
您必须将字符串转换为数组:
placesToVisit: JSON.parse(req.body.placesToVisit),