user2491336
user2491336

Reputation: 187

Store folders in fs.files collection

I would like to create a virtual file system with GridFS.

Actually, i think about to extend the fs.files collection from the GridFS with folder objects.

Folder schema would be like this:

var folder = {
    _id: new ObjectID(),
    name: "Folder1",
    metadata: {
        type: "Folder",
        parentId: ObjectID("xxxxxxxxx")
    }
};

and to get all files and folders by a parentId, which would be a ObjectID and stored in the same collection:

function getFilesAndFolders(parentId) {
    var items = db.fs.files.find({ "metadata.parentId": parentId });

    items.forEach(function (item) {
        switch (item.metadata.type) {
            case "Folder":
                // Do something with the folder
                break;
            case "File":
                // Do something with the file
                break;
            default: break;
        }
    });

    return items;
}

Would be a good practice to extend the db.fs.files collection with a different object or is it better to create separate collection (e.g. db.fs.folders), but with two queries on fs.files and fs.folders to get all items?

Upvotes: 5

Views: 3292

Answers (1)

Stennie
Stennie

Reputation: 65303

There are a few approaches using the standard GridFS implementation that would probably be helpful for your virtual folder concept:

  1. You could save the value of your "virtual folder" path in the GridFS files metadata. Assuming you want to implement a nested folder hierarchy, it would be useful to read the MongoDB data model documentation which includes common patterns to Model Tree Structures.

  2. GridFS has a concept of "buckets" or namespaces. The default name space is fs, but you could use a different namespace for each of your "virtual folders" or content types if they are relatively flat.

Upvotes: 4

Related Questions