title: validate request body before uploading a file using multer in nodejs
body: <p>I want to upload user profiles according to their school ids
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// import multer
  var multer = require('multer')
  
  // import school and student models
  const { School } = require('./models/school/school.model.js')
  const { Student } = require('./models/student/student.model.js')
  
  // configure multer
  const storage = multer.diskStorage({
      destination: (req, file, cb) =&gt; {
          const dir = `./uploads/schools/${req.body.schoolId}/students`
          fs.exists(dir, exist =&gt; {
              if (!exist) {
                  return fs.mkdir(dir, { recursive: true }, error =&gt; cb(error, dir))
              }
              return cb(null, dir)
          })
      },
      filename: (req, file, cb) =&gt; {
          cb(null, `student-${normaliseDate(new Date().toISOString())}.${file.originalname.split('.')[file.originalname.split('.').length - 1]}`)
      }
  })
  
  var upload = multer({storage: storage}).single('profile')
  
  app.post('/student', function (req, res) {
      // check if submitted school id is valid
      let school = await School.findOne({ _id: req.body.schoolId })
      if (!school)
          return res.send(`School of id ${req.body.schoolId} doesn't exist`)
  
      // upload the profile pic
      upload(req, res, function (err) {
          if (err)
              return res.send(err)
      })
  
      // save the student
      let newStudent = new Student({
          name: req.body.name,
          email: req.body.email,
          school: req.body.schoolId,
          profile: req.file.filename
      })
  
      const saveDocument = await newStudent.save()
      if (saveDocument)
          return res.send(saveDocument).status(201)
      return res.send('New College not Registered').status(500)
  })</code></pre>
  </div>
  </div>
  </p>
  <p>but when I try to access req.body before uploading the profile I get an empty object.</p>
  <p>I would upload the profiles in a tempolary folder and move them later but what if the submitted school id is invalid ?? this will require me to delete the uploaded file. so I want to make sure the submitted details are valid and then upload the profile later save the student.</p>