[英]Mongoose Sub-documents on separate files, how to embed them
我正在定义我的应用程序模型,我为每个模型定义了单独的文件,我的问题是,我需要创建一个使用子文档的模型,但是在另一个文件上,我该如何使用该模式在我的模特? 我的意思是我见过的所有例子都在同一个文件中声明了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。
在此先感谢,我想在单独的文件上定义每个模型以维持秩序。
您可以通过其schema
属性访问Model的架构。 所以这应该工作:
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会为你扩展这些类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.