I am developing an application that uses MongoDB (typegoose) to store file system-like (recursive) documents composed of files and folders. However, I do not know how to query such a schema. For querying, I am provided the following.
- users _id
- the array of folder names in order ex. ['root', 'nestedFolder1', 'nestedFolder2', 'etc...']
- _id of the last folder chosen
The schema is as follows
import { Types } from "mongoose";
interface File {
_id: Types.ObjectId;
fileName: string;
isDir: false;
content: string;
title: string;
description: string;
}
interface FileSystem {
_id: Types.ObjectId;
folderName: string;
isDir: true;
files: File[] | [];
folders: FileSystem[] | [];
}
interface Project {
_id: Types.ObjectId;
projectName: string;
fileSystem: FileSystem;
}
interface User {
_id: Types.ObjectId;
projects: Project[];
}
Update: Here's a replit for reference https://replit.com/@alphacoma18/mongodb-recursive-schema#server.ts
1- Most trivial query, get all FileSystem Documents:
2- Using the $eq operator to match documents with a certain value
3- Using the $in operator to match a specific field with an array of possible values.
4- Using the $and operator to specify multiple conditions
5- Retrieve all documents that are directories and are not empty.
6- All directories that have a folder name that starts with the letter 'n'
Now the tougher queries:
1- count the total number of documents
2- count the total number of documents that are directories
3- Get 'foldername' and 'filename; of all documents that are files.
4- Retrieve the total number of files (isDir: false) in each directory (isDir: true)
5- Recursive structure querying: The FileSystem interface is recursive, because it has both an array of files and an array of folders, which are both of type File[] and FileSystem[].
To query this recursive schema, you can use the $lookup operator in an aggregate pipeline, to make a left join between FileSystem and itself, based on some criteria.