'Upload pdf with express to mongo db

I'm trying to implement pdf upload with express and save it to mongo db . But it was only saving to localy my pc i can't send it to mongo db. Can any one help me how can i upload or access pdf files using multer or any other library.



Solution 1:[1]

As far as I know, you have 2 -maybe 3- ways of using "files" with MongoDB, the approach will depend on your use case (and size of the document):

  1. Store the files directly in the document As you know you can store anything you want in a JSON/BSON document, you just need to store the bytes and your PDF will be part of the document. You just need to be careful about the document size limit of 16Mb.

You can add meta-data for the file in the JSON document, and they are stored in the same place.

For example in Java you will just store byte[] in an attribute, look at his test: https://github.com/mongodb/mongo-java-driver/blob/master/src/test/com/mongodb/ByteTest.java#L188

  1. Use GridFS GridFS allows you to store files of "any size" into MongoDB. The file you are storing is divided in chunks by the driver and stored into smaller documents into MongoDB, when you read it it will be put back in a single file. With this approach, you do not have any size limit.

In this case, if you want to add metadata, you create a JSON document that you store with all the attributes and a reference to the GridFS file.

You can find information about this here: http://docs.mongodb.org/manual/core/gridfs/ and to this Java test: https://github.com/mongodb/mongo-java-driver/blob/master/src/test/com/mongodb/gridfs/GridFSTest.java

  1. Create Reference to an external storage This one is not directly a "MongoDB" use case, but I think it is important to mention it. You can obviously store the files in some special storage and use MongoDB just for the metadata and reference this file. I will take a stupid example but suppose you want to create a Video application, you can store the videos in YouTube and reference this into the document with all your application metadata.

So let's stay on your use case/question, so you can use approaches 1 & 2, and it will depend on the size of the files and how do you access them. If you can give us more information about your application people may have a stronger opinion on the best approach.

If you are looking for people doing this, you can look at this presentation from MongoDB World: http://www.mongodb.com/presentations/translational-medicine-platform-sanofi-0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sagar