简体   繁体   中英

Mongoose / JavaScript - Saving error - undefined object

I am trying to save a match between 2 teams , I am passing the 2 teams through a drop down list.

When I use util.log to output the homeTeam to the console when INSIDE the Team.findByKey method it works successfully and here is the output:

3 Mar 19:52:33 - { name: 'Liverpool',
  _id: 51312074bb176ba624000007,
  __v: 0,
  key: 1362174068837 }

But as soon as I try to do this outside of this method I get the following output which means that when I try to save this as a match, the hometeam appears as just undefined rather than the id of the hometeam :

3 Mar 19:54:09 - [object Object]

My problem is that I am eventually wanting to save both a home team and an away team to the same match in one save. The code for saving a match works when inside the Team.findByKey method which is as follows:

  app.get('/save/matchTest', function(req, res) {
    var key = 1362174006191; // Man Utd 51312036bb176ba624000001
    Team.findByKey(key, function(err, team) {
      util.log(team);
      if(err) {
        util.log("Error occured");
      }
      if(!team) { 
        util.log("The team does not exist");
      }
      var match = new Match({
        hometeam: team._id
      });
      match.save(function(err) {
        if(err) {
          util.log('Error while saving Match: ' + util.inspect(err));
          res.send("An error occured whilst saving the match");
        } else {
          res.send("Saved the match");
        }
      });
    });
  });

But what I want to do is to be able to save a match with the following

var match = new Match({
    hometeam: homeTeam._id,
    awayteam: awayTeam._id
});

Does anyone have any ideas?

Here is the relevant code:

JavaScript

submitMatch = function(){
    var homeId = $("#homeTeamList").val();
    var awayId = $("#awayTeamList").val();

    //alert("home: " + homeId + " away: " + awayId);

    // Frontend sends the data
    var matchForm = {
        homeKey : $('#homeTeamList').val(),
        awayKey : $('#awayTeamList').val()
    };

    // Basic validation
    $.post('/save/match', {'matchForm' : matchForm}, function(response) {
        console.log(response);
    });

};

/save/match

  app.post('/save/match', function(req, res) {
    util.log('Serving request for url [GET] ' + req.route.path);
    // Output to console to test what is being passed to Save Match
    // Entire body passed to console
    //console.log('body: ', req.body);
    // Entire matchForm from body
    //console.log('matchForm: ', req.body.matchForm);
    // Home Key from matchForm
    //console.log('homeKey: ', req.body.matchForm.homeKey);
    // Away Key from matchForm
    //console.log('awayKey: ', req.body.matchForm.awayKey);

    // Get data from match Form
    var matchForm = req.body.matchForm;

    // Check if a match with 2 teams has been submitted
    if(matchForm.homeKey === '' || matchForm.homeKey === undefined ||
        matchForm.awayKey === '' || matchForm.awayKey === undefined){
      // Not a valid match
      util.log('Not valid match');
    } else {
      var homeId = matchForm.homeKey;
      var awayId = matchForm.awayKey;

      var homeTeam = Team.findByKey(homeId, function(err, homeTeam) {
        util.log(homeTeam);
        if(err) {
          util.log("Error occured");
        }
        if(!homeTeam) { 
          util.log("The home team does not exist");
        }
      });

      var match = new Match({
        hometeam: homeTeam._id
      });

      //util.log(match);

    }
  });

In /save/match you're using the value of homeTeam in the Match constructor before it's been set by the callback. You need to create the Match inside both the home and away team findByKey callbacks like this:

Team.findByKey(homeId, function(err, homeTeam) {
  util.log(homeTeam);
  if(err) {
    return util.log("Error occured");
  }
  if(!homeTeam) { 
    return util.log("The home team does not exist");
  }

  Team.findByKey(awayId, function(err, awayTeam) {
    util.log(awayTeam);
    if(err) {
      return util.log("Error occured");
    }
    if(!awayTeam) { 
      return util.log("The away team does not exist");
    }

    var match = new Match({
      hometeam: homeTeam._id,
      awayteam: awayTeam._id
    });
  });
});

To look up the home and away teams in parallel while still keeping your code organized, you'll want to look at using a flow control library like async .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM