mongoose子文件在单独的文件上,如何embedded它们

我正在定义我的应用程序模型,并为每个我定义的模型有单独的文件,我的问题是,我需要创build一个使用子文档的模型,但是在另一个文件上,我如何使用该模式在我的模型上? 我的意思是我见过的所有例子在同一个文件中声明了Child模型和Parent,例如:

var childSchema = new Schema({ name: 'string' }); var parentSchema = new Schema({ children: [childSchema] }); 

我有一个名为user.js文件,它定义了用户模型:

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ _id : Schema.Types.ObjectId, username : String, }); module.exports = mongoose.model( 'User', userSchema ); 

在另一个叫做sport.js文件中,我有另外一个体育运动的模型定义:

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var sportSchema = new Schema({ _id : Schema.Types.ObjectId, name : String }); module.exports = mongoose.model( 'Sport', sportSchema ); 

所以在我的用户模型中,我需要为用户定义的运动定义一个字段,但是我不知道如何定义这个子文档,因为运动定义在另一个文件上,我试过这个:

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var SportsModel = require('sport'); var userSchema = new Schema({ _id : Schema.Types.ObjectId, username : String, sports : [SportsModel] }); module.exports = mongoose.model( 'User', userSchema ); 

但我不知道这是否是正确的方式,因为我输出的是模型,而不是模式。

在此先感谢,我想定义每个模型在单独的文件,以维持秩序。

您可以通过schema属性访问模型的模式。 所以这应该工作:

 var userSchema = new Schema({ _id : Schema.Types.ObjectId, username : String, sports : [SportsModel.schema] }); 

使用ref

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ _id : Schema.Types.ObjectId, username: String, sports : [{ type: Schema.Types.ObjectId, ref: 'Sport' }] }); module.exports = mongoose.model('User', userSchema); 

顺便说一句,在ref ,你可以在查询时使用.populate('sports') ,mongoose会为你扩展这些types。