用于分层数据(例如文件夹>子文件夹>文件 [英] Mongoose Schema for hierarchical data like a folder > subfolder > file

查看:57
本文介绍了用于分层数据(例如文件夹>子文件夹>文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何为文件系统创建分层架构

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'
    }]
});

ref属性只是指示应该在哪个Collection/Model猫鼬中查找所引用的文档,因此如果您查询它,它可以找到它.在这种情况下,我们引用一个父文件夹(一个Folder)和一个孩子列表(这些孩子也是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.

您可以使用Mongoose的populate功能从参考文献中提取详细信息.有关人口和参考的更多信息,请参见 Mongoose文档.

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.

我将isFile更改为Boolean字段是因为我假设您正在尝试存储是/否值?

N.B. I changed isFile to a Boolean field because I assume you are trying to store a yes/no value?

这篇关于用于分层数据(例如文件夹>子文件夹>文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆