我正在使用MEAN堆栈制作应用程序,但无法将数据发布到数据库中。当我按下“提交”按钮时,表单数据将被清除,就像POST成功时一样,但是当我进入数据库时​​,除了ID和__v之外,其中没有任何新文档。

没有引发任何错误,因为有数据正在发布到数据库,但不是正确的数据(请查看页面底部的mongodb文档)

将数据发布到的表单是这样的:

<input name="userName" type="String" class="form-control" id="userName" ng-model="formData.userName" placeholder="Your Name">
      <input name="game" type="String" class="form-control" id="game" ng-model="formData.game" placeholder="The game?">
      <input name="userPoint" type="Number" class="form-control" id="userPoint" ng-model="formData.userPoint" placeholder="Points?">
      <button type="submit" class="btn btn-default" ng-click="createScore()">Submit</button>


这是createScore():

$http.post('/api/scores', $scope.formData)
                        .success(function(data) {
                            $scope.formData = {};
                            $scope.scores = data;
                            console.log(data);
                        })
                        .error(function(data) {
                            console.log('Error: ' + data);
                        });


这是数据库的猫鼬模型:

var Score = mongoose.model("Score", {
    userName: String,
    game: String,
    userPoint: Number
}, "score");


这是我快递的“ app.post()”路线:

app.post("/api/scores", function(req, res){
    Score.create({
        userName:req.body.userName,
        game:req.body.game,
        userPoint:req.body.userPoint
    }, function(err, score) {
            if (err)
                res.send(err);

            Score.find(function(err, score) {
                if (err)
                    res.send(err)
                res.json(score);
            });
        });
});


数据过帐后,mongodb文件文档如下所示:

{
    "_id": {
        "$oid": "54cbf3d1fbaaf10300000001"
    },
    "__v": 0
}


我当时以为名称可能不正确(例如userPoints和userPoint),但我提出了相同的要求。另外,我对此并不陌生,因此,如果您有任何可能有助于具体主题的教程,请随时分享。

编辑1:

我在node.js部分做了console.log(),上面写着req.body.userName,req.body.game等。在日志中,它们全都是未定义的。我一直在网上寻找解决方案,但似乎找不到解决方案。我尝试过在HTML文件中使用“字符串”而不是“文本”创建类型,但这似乎不起作用。有任何想法吗?

最佳答案

好的,所以我解决了我的问题。

我正在尝试以表单数据而不是x-www-form-urlencoded的形式发布。

在我的core.js中,将其放入createScore方法中:

$http({
            method  : 'POST',
            url     : '/api/scores',
            data    : $.param($scope.formData),
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function(response){
            $scope.formData = {};
            $scope.scores = response;
            console.log(response);
        });


我希望这可以帮助别人!

10-01 21:23
查看更多