How do we create a Hierarchical Schema for a file system
var Folder = new Schema({
'name' : String,
'isFile' : Number,
'children' : [Folder]
});
Can we do some thing like this ???
The schema you've used embeds the children folders inside the parents. This would probably work, but it has a couple of problems.
The first is that the size of each folder document could get pretty big, depending on the size of the file system, and you might run into issues with hitting size limits.
The other issue is that it makes it very difficult to directly find documents that aren't at the top level.
A better solution is to store the parent/child relationship as references.
var Folder = new Schema({
name: String,
isFile: Boolean,
parent: {
type: Schema.Types.ObjectId,
ref: 'Folder'
},
children: [{
type: Schema.Types.ObjectId,
ref: 'Folder'
}]
});
The ref property simply indicates in which Collection/Model mongoose should be looking for the referenced document, so it can find it if you query for it. In this case we reference a parent, which is a Folder, and a list of chilren, which are also documents of type Folder.
Storing references to the parent allow you to easily traverse up the tree, the references to the children allow you to generate the tree from the top down.
You can use the populate
functionality of Mongoose to pull in the details from the references. See the Mongoose documentation for more information on population and references.
N.B. I changed isFile
to a Boolean
field because I assume you are trying to store a yes/no value?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With