【问题标题】:MongoDB / Mongoose - Adding new database entry crashes pageMongoDB / Mongoose - 添加新的数据库条目崩溃页面
【发布时间】:2012-12-10 06:39:59
【问题描述】:

我在向我的数据库中添加team 时遇到问题,我目前有一个索引页面,该页面目前仅显示数据库中的所有团队。当我转到下面的team.jadelocalhost:3000/team 时,我输入团队名称并按下提交按钮。然后,当我转到索引页面时,它就在那里,我的新团队就在那里。

但是当我按下提交按钮时,我实际上得到一个错误提示:

Express
500 TypeError: Cannot read property 'teamName' of undefined
at module.exports (/home/declan/nodeapps/tournamentManager/routes/index.js:126:24)
at callbacks (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:160:37)
at param (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:134:11)
at pass (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:141:5)
at Router._dispatch (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:169:5)
at Object.router (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:32:10)
at next (/home/declan/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.handle (/home/declan/nodeapps/tournamentManager/app.js:34:5)
at next (/home/declan/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.static (/home/declan/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61)

我不知道为什么会这样,index.js 的第 126 行实际上是下面的这一行:

var name = teamForm.teamName;

这是创建新数据库条目的第一行之一,因此如果它无法读取该属性,则不会将其添加到数据库中。这是我的想法,但是当我重新加载索引页面时,有我的新数据库条目,那么您为什么认为它不起作用?

index.js @ 路由

/**
  * Add a new Team to database
  */
  app.post('/team', function(req, res) {
    util.log('Serving request for url[GET] ' + req.route.path);
    var teamForm = req.body.teamForm;
    var name = teamForm.teamName;

    var newTeam = new Team();
    newTeam.name = name;

    newTeam.save(function(err, savedTeam){
      var message = '';
      var retStatus = '';
      if(!err){
        util.log('Successfully created team with Name : ' + name);
        message = 'Successfully created new team : ' + name;
        retStatus = 'success';
      } else {
        util.log('Error while creating team : ' + name + ' error : ' + util.inspect(err));
        if(err.code === 11000){
          message = 'Team already exists';
        }
        retStatus = 'failure';
      }
      res.json({
        'retStatus' : retStatus,
        'message' : message
      });
    });
  });

team.jade @views(html模板,你可以看到需要的id等)

extends index

block content
    div.row-fluid
        div.span9
            h2 New Team
            div.well.sidebar-nav
                div.teamList
                    form.form-horizontal(method="post", id="team-form")
                        div.control-group
                            label.control-label(for="teamName") Team Name :
                            div.controls
                                input.input-small(type="text", id="teamName")
                        div.control-group
                            div.controls
                                button#teamConfirm.btn.btn-primary.btn-mini(href='#') To DB
                br
                p This page is used to demonstrate how an 8 team single elimination tournament would be represented in the final design of my project. The pseudo code conjured up in my initial hand-in document was originally used here to produce the same result. The pseudo code helped create this set of seeded brackets, so that the matches correspond to the seeds of the tournament. For the 8 team bracket, I worked back through from the final, where seeds 1 and 2 should face each other, until I was left at round 1 of the brackets. This was used to give myself a 'new' set of seeds which were in the correct order to just be placed into these brackets.
        div.span3
            div.well.sidebar-nav
                h4 To-Do List:
                p - Enter list of teams manually from this page.
                p - Do a test to show a bracket with random seed.
                p - Show rankings after tournament

team.js@js

var newTeam = function(){
    $('#teamConfirm').click(function(){
        newTeam.teamForm();
    });
};

newTeam.teamForm = function(){

    var teamForm = {
        teamName : $('#teamName').val()
    };
    // Basic validation
    $.post('/team', {'teamForm' : teamForm}, function(response) {
            console.log(response);
    });
};

newTeam();

index.js@js

var Main = {};

Main.loadScript = function(url){
  var footer = document.getElementById('footer');
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;

  footer.appendChild(script);
}

$(document).ready(function(response){
  Main.loadScript('js/login.js');
  Main.loadScript('js/signup.js');
  Main.loadScript('js/team.js');
});

【问题讨论】:

  • 该错误的原因是因为 teamForm 未定义。现在为什么它未定义是另一个问题......
  • 正确,它说它未定义,这就是它导致崩溃的原因,但在那条线上,如果它未定义,我不会认为它会创建新的数据库条目

标签: javascript mongodb mongoose database


【解决方案1】:

我认为这是因为 req.body 没有被解析为 JavaScript 对象(它仍然是 JSON 字符串)。首先检查你是否在使用

app.use(express.bodyParser());

之前任何路线。如果不是这样,请尝试使用.ajax 而不是.postcontentType 设置:

$.ajax({
    // some other settings
    contentType : "application/json"
});

可能是内容类型混乱,Express 没有解析从客户端接收到的 JSON 字符串。您可能会尝试的另一件事是简单地做(在​​服务器端):

app.post('/team', function(req, res) {
    var body = JSON.parse( req.body );
    // other code
}

也许用try{}catch{} 块包装附加行。

【讨论】:

  • 是的,我在我的app.js 文件中设置了app.use(express.bodyParser());。如果我将JSON.parse 代码行添加到我的app.post 中,我会收到以下错误:Express 500 SyntaxError: Unexpected token o at Object.parse (native) 有什么想法吗?
  • 我之前没有使用过这些 ajax 调用,所以我尝试使用您的第二个选项,因为我不知道如何使用 $.ajax 进行编码
  • 如果我使用您的JSON.parse,它也不会向数据库添加任何内容
  • 这是错误发生的顺序:23 Dec 15:10:18 - Serving request for url[GET] /team23 Dec 15:10:18 - Successfully created team with Name : Czech Republic23 Dec 15:10:18 - Serving request for url[GET] /teamTypeError: Cannot read property 'teamName' of undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 2012-11-27
  • 1970-01-01
相关资源
最近更新 更多