Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking 2 mongoose schemas

I have two Schemas, a Team and a Match. I want to use the Team Schema to identify the Teams in the Match Schema. So far, here is my Team and Match JS files. I want to link the Team Schema to my Match Schema so that I can identify the home or away team simply, and so that I am storing in the Match Schema an actual Team object.

This way I can refer to the home team for example as Match.Teams.home.name = England (this is just an example of course)

Team.js

'use strict';

var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var validatePresenceOf = function(value){
  return value && value.length; 
};

var getId = function(){
  return new Date().getTime();
};

/**
  * The Team schema. we will use timestamp as the unique key for each team
  */
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 = mongoose.model('Team', Team);

And here is what I am trying to do with Match.js

'use strict';

var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TeamSchema = require('mongoose').model('Team');

var validatePresenceOf = function(value){
  return value && value.length; 
};

var toLower = function(string){
  return string.toLowerCase();
};

var getId = function(){
  return new Date().getTime();
};

/**
  * The Match schema. Use timestamp as the unique key for each Match
  */
var Match = new Schema({
  'key' : {
    unique : true,
    type : Number,
    default: getId
  },
  'hometeam' : TeamSchema,
  'awayteam' : TeamSchema
});

module.exports = mongoose.model('Match', Match);
like image 973
germainelol Avatar asked Feb 06 '13 13:02

germainelol


2 Answers

Your solution: Use the actual schema, rather than a model that uses the schema:

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

To

module.exports = {
    model: mongoose.model('Team', Team),
    schema: Team
};

and then var definition = require('path/to/js'); that, and use definition.schema instead of a model directly

like image 71
bevacqua Avatar answered Oct 20 '22 02:10

bevacqua


You don't want to nest schemas.

Try Population in Mongoose: http://mongoosejs.com/docs/populate.html That will solve your problem.

like image 33
Yann Eves Avatar answered Oct 20 '22 04:10

Yann Eves