我似乎无法正确配置模型和路由器以通过猫鼬将多个对象发布到数组。这是我的设置:
//Schema
const PickSchema = new Schema({
pick: {
type: String,
required: true,
unique: true
},
team: {
type: String,
required: true
},
player: {
type: String,
required: true,
unique: true
}
})
const DraftSchema = new Schema({
draftboard: [ PickSchema ]
})
module.exports = DraftBoard = mongoose.model('user_draftboard', DraftSchema);
//Router
router.post('/', (req, res) => {
const newDraft = new DraftBoard({
draftboard: [{
pick: req.body.pick,
team: req.body.team,
player: req.body.player
}]
});
newDraft.save().then(newdraftboard => res.json(newdraftboard))
.catch(err => res.status(500).json({ msg: 'internal error'})
)});
使用邮递员,我可以将一个对象发布到数组中,但是我的有效负载可能是一个对象数组,因此我需要发布多个对象,并且当我在邮递员中对其进行测试时,我得到一个错误:
起作用的邮递员正文:
{
"pick": "2",
"team": "Washington Redskins",
"player": "Chase Young"
}
POSTMAN中的JSON响应
{
"_id": "5e960a06ff3a7b3c88e680fd",
"draftboard": [
{
"_id": "5e960a06ff3a7b3c88e680fe",
"pick": "2",
"team": "Washington Redskins",
"player": "Chase Young"
}
],
"__v": 0
}
但是多个对象不起作用:
{
"pick": "2",
"team": "Washington Redskins",
"player": "Chase Young"
},
{
"pick": "3",
"team": "Detroit Lions",
"player": "Jeff Odukah"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>SyntaxError: Unexpected token , in JSON at position 83
有什么想法吗?谢谢!
答案 0 :(得分:0)
我建议您将 POST请求数据放入数组中。像这样:
[{
"pick": "2",
"team": "Washington Redskins",
"player": "Chase Young"
},
{
"pick": "3",
"team": "Detroit Lions",
"player": "Jeff Odukah"
}]
请记住,您可以更改多个对象,它们只需要位于数组中即可。或者,您可以只发出两个不同的POST请求,我发现它们更好,更简单。您不必自己发疯!
希望对您有所帮助,并解决您的问题。如果您需要更多帮助或帮助,请发表评论!