I am using nodeJS, express and mongoose. I am having a schema of form which also uploads multiple pictures. To upload the pictures I am using multer. In multer, I am using multer.fields() to upload the pic with specific own name of key to upload the pic like father_pic, mother_pic and brother_pic. Now Issue is that, There can be more than one brother so How I can upload multiple pictures for the brother pic related to his name and profession?
Model Schema
const familyDetailsSchema = new mongoose.Schema(
{
language:{
type:String,
require:true
},
father:{
fatherName:{
type:String,
require:true
},
fatherProfession:{
type:String,
require:true
},
fatherImage:{
type:String,
require:true
}
},
mother:{
motherName:{
type:String,
require:true
},
motherProfession:{
type:String,
require:true
},
motherImage:{
type:String,
require:true
}
},
brothers:[
{
name:String,
profession:String,
image:String,
}
],
details:{
type:String,
require:true
},
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdAt: {
type: Number
},
updatedAt: {
type: Number,
}
},
{
timestamps:true,
}
)
Here’s the code of route
router.post('/familyDetails',
[
upload.fields([
{
name: 'father_pic',
},
{
name: 'mother_pic',
},
{
name:'brother_pic'
}
]),
],
async (req, res) => {}
2
Answers
To treat this input as array you can use multer.array, follow this simple example:
To understand with more details you can use multer docs at npm: https://www.npmjs.com/package/multer
Did you consider using
.any()
method of the Multer, that will enable you to upload files with any name. Then, you don’t have to worry about the number of files and the file names.