DBrefs - Cast to ObjectId failed for value

335 views
Skip to first unread message

Declan Elcocks

unread,
Feb 6, 2013, 4:13:32 PM2/6/13
to mongoo...@googlegroups.com

I have a Team Schema holding details about teams, and a Match Schema to store these teams in. I am trying to make it so that the home/away teams in the Match Schema are references to the Team object. I have put my code below, I'm getting an error when saving the Team but I can't help but feel I have done something wrong with the Schema's or the saving of the Match. Can anyone help?

So far I have the following code:

Team.js extract

var Team = new Schema({
  'key' : {
    unique : true,
    type : Number,
    default: getId
  },
  'name' : { type : String,
              validate : [validatePresenceOf, 'Team name is required'],
              index : { unique : true }
            }
});

module.exports.Schema = Team;
module.exports.Model = mongoose.model('Team', Team);

Match.js extract

var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Team = require('../schemas/Team').Schema;

var Match = new Schema({
  'key' : {
    unique : true,
    type : Number,
    default: getId
  },
  'hometeam' : {
    type : Schema.ObjectId,
    ref : 'Team'
  },
  'awayteam' : {
    type : Schema.ObjectId,
    ref : 'Team'
  }
});

module.exports = mongoose.model('Match', Match);

index.js

  app.get('/match', function(req, res) {
    var key = 1356136550152; // Reading
    Team.findByKey(key, function(err, team) {
      if(err) {
        res.send("An error occured");
      }
      if(!team) { 
        res.send("The team does not exist");
      }
      var match = new Match();
      match.hometeam = team;
      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");
        }
      });
    });
  });

ERROR:

Error while saving Match: { message: 'Cast to ObjectId failed for value "{ name: \'testTeam\',\n  _id: 50d500663ca6067226000001,\n  __v: 0,\n  key: 1356136550152 }" at path "hometeam"',
  name: 'CastError',
  type: 'ObjectId',
  value: 
   [ { name: 'testTeam',
       _id: 50d500663ca6067226000001,
       __v: 0,
       key: 1356136550152 } ],
  path: 'hometeam' }
Reply all
Reply to author
Forward
0 new messages