Save file uploads to Mongo DB using Express Save file uploads to Mongo DB using Express mongodb mongodb

Save file uploads to Mongo DB using Express


Okay so the tutorial you are following is using the example of taking the temporary file information from the upload, and moving that file to another location.

So as it stand, you have the target_path variable in your code which shows where to find the file on disk. So if you want to store a reference, there you have it, and future reads of your mongo document will have that path information so you could access the file again.

As you have said, you probably don't want to be passing in the whole res.body but just access properties of it like this and construct your own document in which to insert/update whatever. Information on accessing info on the File is in the express documentation.

If you decide you want to put the File Content into your mongo document, then it is just a matter of reading the file content in. Here the core node documentation for File System operators may be of assistance to you. Particularly the read function.

From a MongoDB standpoint you can just add that content to any document field, it won't care and handles binary types. Provided that your size is under the 16MB BSON limitation.

Over that limit and maybe of interest to you, would be GridFS. And for reference there is this question on SO that may provide you with some insight on how to do this.