0

I want to save a file using node JS to save a file in an attribute using mongoose schema to save an entry in mongoose collection.

What should be the type of the attribute in the schema?
And how can I save the file to this attribute?

I used the regular save function, but it saved all the attributes posted by the router except this one attribute of the image

zx485
  • 28,498
  • 28
  • 50
  • 59
ultimate_beaver
  • 85
  • 2
  • 12

2 Answers2

1

You should not save a file in mongoose, instead you should upload the file, and save the path to the file in mongoose, for this you will just need a string field to save the path

Ronny vdb
  • 2,324
  • 5
  • 32
  • 74
  • and how can I select the directory in which the upload will save the file to + how can I link the entry in mongoose with the file. sorry for disturbance. I'm a beginner – ultimate_beaver Feb 25 '17 at 18:33
  • please post your code that you are using to upload the file – Ronny vdb Feb 25 '17 at 18:34
  • I'm using a form group to upload and '''
    '''
    – ultimate_beaver Feb 25 '17 at 18:37
  • this is just the html form, in your server-side code you need to handle the file upload, and there you set the path where you want to store the image. Once you have handled the file upload you will have the path that you can save to the db – Ronny vdb Feb 25 '17 at 18:40
  • 5
    Care to elaborate why he should only save the path? While I agree that saving binary data in most databases are not a good idea, MongoDB handles binary data differently from a SQL database like MySQL, for example, and there are so real use cases you saving binary data in MongoDB is preferable. Simply saying "don't do it" doesn't help at all. – vegidio Jun 17 '18 at 06:25
  • I agree with vegidio, you should elaborate why not do this... – Wes Guirra Dec 03 '19 at 23:02
1

Here the Mongoose way: https://mongoosejs.com/docs/schematypes.html#buffers

I dislike keeping resources in sync (filesystem & Db Record), at some point (usually in prod) there will be records without files or vice versa. I think the file should be where it belongs context-wise, whenever possible architecture-wise.

MongoDB/Mongoose is perfectly ready (maybe 2017 it wasn’t ‍♂️

Heavy files (16Mb+) should he stored using GridFs.

faebster
  • 727
  • 7
  • 13