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);
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
You don't want to nest schemas.
Try Population in Mongoose: http://mongoosejs.com/docs/populate.html That will solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With