36

I want to save a user selected file to MongoDB. How do I correctly add the file to the BSON object in order to add it to MongoDB? If my approach is incorrect please point in the right direction.

Below is the client code. This jQuery functions gathers the text (need help on the file part) on every input field and sends it to the server as a BSON object.

$('#add').click(function()
            {
                console.log('Creating JSON object...');
                var classCode = $('#classCode').val();
                var professor = $('#professor').val();
                var description = $('#description').val();
                var file = $('#file').val();

                var document = 
                {
                    'classCode':classCode,
                    'professor':professor,
                    'description':description,
                    'file':file,
                    'dateUploaded':new Date(),
                    'rating':0 
                };
                console.log('Adding document.');
                socket.emit('addDocument', document);
            });

The HTML of the form:

   <form>
        <input type = 'text' placeholder = 'Class code' id = 'classCode'/>
        <input type = 'text' placeholder = 'Document description' id = 'description'/>
        <input type = 'text' placeholder = 'Professor' id = 'professor'/>
        <input type = 'file' id = 'file'/>
        <input type = 'submit' id = 'add'/>
    </form>

The server side code in CoffeeScript:

#Uploads a document to the server. documentData is sent via javascript from submit.html
            socket.on 'addDocument', (documentData) ->
                console.log 'Adding document: ' + documentData
                db.collection 'documents', (err, collection) ->
                    collection.insert documentData, safe:false
                    return

3 Answers 3

52

If your files are small enough (under 16 megabytes), instead of adding the complexity of GridFS, you can just embed the files into BSON documents.

BSON has a binary data type, to which any of the drivers should provide access.

If your file is a text file you can just store it as a UTF8 string.

3
  • 5
    Can you show example how to use this type? I have file on my filesystem - how to put it into database? Commented Jul 31, 2017 at 13:11
  • 1
    I also didn't get any good documentation or example anywhere for uploading small files without Gridfs
    – Adil
    Commented Sep 6, 2017 at 6:04
  • You could post a new question about how to use your driver's binary data type with data from a file. Commented Sep 7, 2017 at 15:32
23

To store files in MongoDB you should try to use GridFS.
You can find some tutorials about working with GridFS (example).
Check your MongoDB Driver's API and try to implement it in your project

5
  • 2
    I have been reading about GridFS, but I can't find an example that shows how to send the file from the client to the server in order to save it in the GridFS. Got any sources?
    – user810606
    Commented Dec 17, 2012 at 5:59
  • 1
    I'm not good at Node.js, but you can look at some tutorials (gist.github.com/1071705 and prazjain.wordpress.com/2012/04/18/…). In this tutorials they save file to a regular filesystem, and you should replace fs with GridFS code Commented Dec 17, 2012 at 6:11
  • 1
    First of all, try to upload file to your file system to ensure that your code works. And then replace it with GridFs Commented Dec 17, 2012 at 6:14
  • Oh, I thought I could just save the file directly from the client to the database on the server side without storing it temporarily in my server's filesystem first. Anyway thanks for the links I will keep reading.
    – user810606
    Commented Dec 17, 2012 at 6:50
  • 1
    You can just save it to GridFS, from server side. I told you to save your file to fs just to test if your upload functionality works. And then implement GridFS instead of filesystem. Commented Dec 17, 2012 at 6:58
4

When to Use GridFS

From official doc: https://docs.mongodb.com/manual/core/gridfs/#when-to-use-gridfs

In MongoDB, use GridFS for storing files larger than 16 MB.

In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem.

  • If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed.

  • When you want to access information from portions of large files without having to load whole files into memory, you can use GridFS to recall sections of files without reading the entire file into memory.

  • When you want to keep your files and metadata automatically synced and deployed across a number of systems and facilities, you can use GridFS. When using geographically distributed replica sets, MongoDB can distribute files and their metadata automatically to a number of mongod instances and facilities.

Do not use GridFS if you need to update the content of the entire file atomically. As an alternative you can store multiple versions of each file and specify the current version of the file in the metadata. You can update the metadata field that indicates “latest” status in an atomic update after uploading the new version of the file, and later remove previous versions if needed.

Furthermore, if your files are all smaller the 16 MB BSON Document Size limit, consider storing the file manually within a single document instead of using GridFS. You may use the BinData data type to store the binary data. See your drivers documentation for details on using BinData.

1
  • 3
    Sir i have a question
    – user9551058
    Commented Sep 27, 2019 at 2:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.