0

Is there a way to upload files directly to a mongodb schema?

I'm currently developing an API. There's a form that consists of multiple fields including 3 different files (as in PDFs) but I haven't found a way to store them in the schema so it's fast to access.

I think the schema should look something like this:

const SomeSchema = mongoose.schema({
   data: { 
     type: String,
     required: true
   },
   data:{
     type: Date,
     required: true
   }
    data:{
     type: String,
     required: true
   }
   file:
   type: File(?),
   required: true
)}

But I don't think this is correct since I have watched some tutorials and they don't store files in the same collection. Is it not possible?

2
  • You can store the binary data of the file as a Buffer. Commented Sep 1, 2022 at 5:06
  • 1
    Is there a special reason to store a file on mongoose ? Because it won't the best practice for performance. Commented Sep 1, 2022 at 14:09

1 Answer 1

1

You can store the binary data of the file as Buffer in your document as Seyyed said. For that you have to edit the file field on your mongoose schema as shown:

file:{
data: Buffer,
contentType: String
}

Or else we can upload the file to the uploads folder in your project directory using multer and you can save the path to the file on you database. You can use this link as your reference https://www.section.io/engineering-education/uploading-files-using-multer-nodejs/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.