链接2个猫鼬模式 [英] Linking 2 mongoose schemas
问题描述
我有两个模式,一个Team
和一个Match
.我想使用Team Schema
来标识Match Schema
中的团队.到目前为止,这是我的Team and Match JS文件.我想将团队架构链接到我的比赛架构,以便我可以简单地识别主队或客队,以便在比赛架构中存储一个实际的团队对象.
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.
这样,我可以将主队称为例如Match.Teams.home.name = England
(当然这只是一个例子)
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);
这就是我想用Match.js做的事情
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);
收件人
module.exports = {
model: mongoose.model('Team', Team),
schema: Team
};
然后var definition = require('path/to/js');
,然后直接使用definition.schema
而不是模型
and then var definition = require('path/to/js');
that, and use definition.schema
instead of a model directly
这篇关于链接2个猫鼬模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!