Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store folders in fs.files collection

Tags:

mongodb

gridfs

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?

like image 250
user2491336 Avatar asked Jan 21 '14 09:01

user2491336


1 Answers

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.

like image 117
Stennie Avatar answered Oct 02 '22 19:10

Stennie