6

我有两个模式, aTeam和 a Match。我想使用Team Schema来识别Match Schema. 到目前为止,这是我的 Team 和 Match JS 文件。我想将 Team Schema 链接到我的 Match Schema,以便我可以简单地识别主队或客队,并在 Match Schema 中存储一个实际的 Team 对象。

这样我就可以将主队称为Match.Teams.home.name = England(当然这只是一个例子)

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 做的事情

'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);
4

3 回答 3

3

您的解决方案:使用实际架构,而不是使用架构的模型:

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

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

然后var definition = require('path/to/js');那个,definition.schema直接使用而不是模型

于 2013-02-06T13:52:14.353 回答
2

您不想嵌套模式。

尝试猫鼬中的人口:http: //mongoosejs.com/docs/populate.html 这将解决您的问题。

于 2014-04-30T22:09:04.290 回答
2

尝试Schema.Types.ObjectId在 Match.js 中使用:

hometeam: { type: Schema.Types.ObjectId, ref: 'Team' } awayteam: { type: Schema.Types.ObjectId, ref: 'Team' }

于 2020-05-24T08:35:27.327 回答