用于分层数据(如文件夹)的Mongoose模式>;子文件夹>;文件
如何为文件系统创建分层架构用于分层数据(如文件夹)的Mongoose模式>;子文件夹>;文件,mongoose,Mongoose,如何为文件系统创建分层架构 var Folder = new Schema({ 'name' : String, 'isFile' : Number, 'children' : [Folder] }); 我们可以这样做吗?您使用的模式将子文件夹嵌入父文件夹中。这可能行得通,但有几个问题 首先,根据文件系统的大小,每个文件夹文档的大小可能会变得相当大,并且您可能会遇到大小限制问题 另一个问题是,直接查找非顶级文档非常困难 更好的解决方案是将父/子关系存储为引用 var Folder
var Folder = new Schema({
'name' : String,
'isFile' : Number,
'children' : [Folder]
});
我们可以这样做吗?您使用的模式将子文件夹嵌入父文件夹中。这可能行得通,但有几个问题 首先,根据文件系统的大小,每个文件夹文档的大小可能会变得相当大,并且您可能会遇到大小限制问题 另一个问题是,直接查找非顶级文档非常困难 更好的解决方案是将父/子关系存储为引用
var Folder = new Schema({
name: String,
isFile: Boolean,
parent: {
type: Schema.Types.ObjectId,
ref: 'Folder'
},
children: [{
type: Schema.Types.ObjectId,
ref: 'Folder'
}]
});
ref属性只是指示mongoose应该在哪个集合/模型中查找引用的文档,因此如果您查询它,它可以找到它。在本例中,我们引用一个父文件夹和一个chilren列表,它们也是Folder类型的文档
存储对父级的引用使您能够轻松地向上遍历树,对子级的引用使您能够自上而下地生成树
您可以使用Mongoose的populate
功能从参考中获取详细信息。有关总体和参考的更多信息,请参阅
var Folder = new Schema({
name: String,
isFile: Boolean,
parent: {
type: Schema.Types.ObjectId,
ref: 'Folder'
},
children: [{
type: Schema.Types.ObjectId,
ref: 'Folder'
}]
});
注意:我将
isFile
更改为Boolean
字段,因为我假设您正在尝试存储yes/no值?您使用了mongoose树或mongoose物化在MongoDB集合上存储分层数据有一些有文档记录的方法,我在下面引用:
这些方法中的任何一种都可以由您自己或通过mongoose插件来实现,您可以通过搜索“tree”来找到它。所以matthewtole如果我理解正确的话,会是这样的吗
const FolderSchema = new Schema({
name: String,
isFile: Boolean,
parent: {
type: Schema.Types.ObjectId,
ref: 'Folder'
},
files: [{
name: { type: String, required: true, max: 100 },
encodedName: { type: String, required: false, max: 100, default: null },
}],
owner: { type: ObjectId, ref: 'User' },
team: { type: ObjectId, ref: 'Team' }
});
const Folder = mongoose.model('folders', FolderSchema);
module.exports = {
Schema: FolderSchema,
Folder
};
对这件事进行一点详细的阐述是值得赞赏的,但是“文件夹”参考号放在哪里呢?
Model.find( { path: /,Programming,/ } )
Model.find( { path: /^,Books,/ } )
Model.find( { path: /,Books,$/ } )
const FolderSchema = new Schema({
name: String,
isFile: Boolean,
parent: {
type: Schema.Types.ObjectId,
ref: 'Folder'
},
files: [{
name: { type: String, required: true, max: 100 },
encodedName: { type: String, required: false, max: 100, default: null },
}],
owner: { type: ObjectId, ref: 'User' },
team: { type: ObjectId, ref: 'Team' }
});
const Folder = mongoose.model('folders', FolderSchema);
module.exports = {
Schema: FolderSchema,
Folder
};