【问题标题】:Linking 2 mongoose schemas链接 2 个猫鼬模式
【发布时间】:2020-05-24 16:35:27
【问题描述】:

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

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

团队.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);

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我已经按照你说的更改了团队导出。在 Match.js 文件中,我现在有 var definition = require('Team.js'); 并且我将 hometeam 存储为 definition.schema 但我收到 cannot find module Team.js 的错误,知道吗?
    • 抱歉再次发表评论,但我通过放置完整路径解决了这个问题,现在得到 TypeError: Undefined type at hometeam` 并询问我是否正在嵌套模式
    【解决方案2】:

    您不想嵌套模式。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-02-14
        • 2016-08-05
        • 2019-06-04
        • 2021-02-14
        • 2015-04-13
        • 2020-09-18
        • 1970-01-01
        • 2016-11-21
        • 2012-02-02
        相关资源
        最近更新 更多