for upload an image into a object, this object must exist before upload?

Viewed 24

I have this function in nodejs to save an user with an image file name.

save: function(req, res) {
  var params = req.body;
  console.log(JSON.stringify(req.files.image.path));
  var file = req.files.image.path;
  // // var file_split = file_path.split('\\');

  // // ** Adventencia ** En linux o mac
  var file_split = file.split('/');

  // // Nombre del archivo
  var file_name = file_split[2];
  // console.log(file_name);

  // // Extensión del archivo
  var ext_split = file_name.split('.');
  console.log(ext_split);
  var file_ext = ext_split[1];
  console.log(file_ext);

  if (
    file_ext != 'png' &&
    file_ext != 'jpg' &&
    file_ext != 'jpeg' &&
    file_ext != 'gif'
  ) {
    fs.unlink(file, (err) => {
      return res.status(400).send({
        status: 'error',
        message: 'La extensión del archivo no es valida.',
      });
    });
  } else {
    var image = file_name;
  }
  var user = new User();

  user.name = params.name;
  user.email = params.email;
  user.age = params.age;
  user.image = image;

  user.save((err, userStored) => {
    if (err) {
      console.log('error', err);
      return res.status(500).send({
        message: 'Error al guardar el usuario',
      });
    }
  });
};

with postman I add the user name, email, age and image with body form-data

and I get this error

error Error: User validation failed: image: Cast to Object failed for value "jOmiGx3Ja_5jUnAEi5MuPSMC.jpg" (type string) at path "image"

do I have to separate the upload image with the save user? the user must exist before upload an image?

I dont know how to fix it.

0 Answers
Related