从前端向后端发送数据时出现以下错误
message:
'Cast to Array failed for value "[object Object]" at path "tickets"',
name: 'CastError',
stringValue: '"[object Object]"',
kind: 'Array',
value: '[object Object]',
path: 'tickets',
reason: [MongooseError] } },
_message: 'event validation failed',
name: 'ValidationError' }
我不认为问题在于模式的设置方式。我认为这是因为我正在将图像发布到后端并使用data.append附加其余数据。这是multer文档建议发送数据的方式。
这是我的功能,用于将数据发送到后端(我删除了其他变量以使其易于阅读):
createEvent = e => {
e.preventDefault()
let data = this.state.userEvent.image
data.append("tickets", this.state.userEvent.tickets)
console.log('tickets', this.state.userEvent.tickets)
console.log('datasent', data)
axios.post(`${process.env.REACT_APP_API}/image`, data)
.then().catch(err => {
console.log("imgerr", err)
})
}
控制台日志不会让我看到发送到后端的确切信息,但是从当前状态看,它是正确的。
这是后端架构的相关部分(我删除了其他变量以使其易于阅读):
const mongoose = require('mongoose')
const Event = mongoose.model('event', {
tickets: {
type: [{
ticketType: String,
price: Number,
numberOfTickets: Number,
startSelling: String,
stopSelling: String,
startSellingTime: Date,
stopSellingTime: Date,
ticketDescription: String,
refunds: {
optionSelected: String,
refundUntil: Date,
howToResell: String,
resellAtSpecificPrice: Number,
minimumPrice: Number,
nameOfResoldTickets: String
}
}]
},
})
module.exports = Event
这是控制器的相关部分(我删除了其他变量以使其易于阅读)
const Event = require('../models/events')
module.exports = (req, res) => {
console.log('req body', req.body)
console.log('req body tickets', req.body.tickets)
let newEvent = {
tickets: req.body.tickets
}
Event.create(newEvent)
.then(data => {
console.log('data', data)
res.send(data)
})
.catch(err => console.log(err))
}
当我使用邮递员发布以下内容时:
{
"title": "Postman",
"tickets": [{
"ticketType": "Early Bird",
"price": "10",
"numberOfTickets": "100",
"startSelling": "eventstarts",
"stopSelling": "eventends",
"startSellingTime": "2019-12-31T12:30:00",
"stopSellingTime": "2019-12-31T12:30:00",
"ticketDescription": "ticketzzz",
"refunds": {
"optionSelected": "yes",
"refundUntil": "2019-12-31T12:30:00",
"howToResell": "xyz",
"resellAtSpecificPrice": "40",
"minimumPrice": "30",
"nameOfResoldTickets": "asdf"
}
}]
}
我没有收到该错误,但它返回:
{
"_id": "5ddedd850504750620e620bb",
"title": "Postman",
"tickets": [
{
"_id": "5ddedd850504750620e620bc",
"ticketType": "Early Bird",
"price": 10,
"numberOfTickets": 100,
"startSelling": "eventstarts",
"stopSelling": "eventends",
"startSellingTime": "2019-12-31T12:30:00.000Z",
"stopSellingTime": "2019-12-31T12:30:00.000Z",
"ticketDescription": "ticketzzz"
}
],
"__v": 0
}
奇怪的是它有两个单独的ID
知道我要去哪里哪里吗?