Node.js Mongoose子文档位于单独的文件上,如何嵌入它们
我正在定义我的应用程序模型,我为我定义的每个模型都有单独的文件,我的问题是,我需要创建一个使用子文档的模型,但它位于另一个文件上,我如何在我的模型上使用该模式?我的意思是,我看到的所有示例都在同一个文件中声明了子模型和父模型,例如:Node.js Mongoose子文档位于单独的文件上,如何嵌入它们,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在定义我的应用程序模型,我为我定义的每个模型都有单独的文件,我的问题是,我需要创建一个使用子文档的模型,但它位于另一个文件上,我如何在我的模型上使用该模式?我的意思是,我看到的所有示例都在同一个文件中声明了子模型和父模型,例如: var childSchema = new Schema({ name: 'string' }); var parentSchema = new Schema({ children: [childSchema] }); 我有一个名为user.js的文件,它定
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将为您扩展这些类型。它本质上相当于SQL中的外键。但ref只适用于内置的ObjectId类型。使用populate可能非常危险。对于基于文档的数据库,如MongoDB,这几乎是一种反模式。如果您不需要在用户之间共享您的运动,最好使用子文档。基本上,记住MongoDB不是关系数据库是很重要的。@catalyst294您可能是对的。但是你说的方式听起来像是纯粹的观点。你没有给出任何危险的原因,也没有给出任何表明它是反模式的参考。(值得一提的是,一个简单的谷歌搜索不会找到任何这样的参考资料。)我理解你是在试图提供帮助,但如果你给出理由和支持,它可能会对其他用户有更多帮助。@tandrewnichols猫鼬会欺骗你,让你认为填充是一个非常快速简单的操作。但populate所做的是生成另一个查询。我曾经在一些项目中工作过,这些项目的模式设计得很糟糕,而且成本也很高。对于document DBs,您应该支持数据复制,而不是在您能够完成的地方进行这些填充(基本上是连接)。乡亲们