I'm having some problems with a function I'm using where it checks for files in a request body and then performs an action depending on what files are there. The thing I can't understand is, when both file fields are populated it works exactly as I'd expect.
// Check to see if any files were uploaded.
// Using isEmpty because even without uploads, req.files returns an empty object.
if (!isEmpty(req.files)) {
// Checking if an avatar file was uploaded and creating document for it using ifFile().
// Then adding new document to userInfo object (which will be used to create new User document).
if (req.files['avatar'][0]) {
avatar = await ifFile(req, 'avatar');
userInfo.avatar = avatar;
}
// Checking if an avatar file was uploaded and creating document for it using ifFile().
// Then adding new document to userInfo object (which will be used to create new User document).
if (req.files['coverphoto'][0]) {
coverphoto = await ifFile(req, 'coverphoto');
userInfo.coverphoto = coverphoto;
}
// Creating async function for new User document generation to ensure the password is encrypted by encryptPassword() before being returned.
const createNewUser = async () => {
const newUser = new User(userInfo);
await encryptPassword(newUser);
return newUser;
};
// Assign the new User document returned by the createNewUser() function to a new user vairable to use to update avatar/coverphoto updates.
const user = await createNewUser();
return user;
} else {
const user = new User(userInfo);
await encryptPassword(user);
return user;
}
What happens when only one field is populated: if it is the avatar field, which is first to be checked, the avatar file gets processed correctly and then it checks the coverphoto (which isn't there) and then immediately returns outside of the original if statement without calling createNewUser(). When the coverphoto field is populated and the avatar isn't, it gets to the avatar field check and then immediately does the same thing when the condition isn't met. It can't be an issue with req.files because it works just fine when there are both files present. It's the if() statement returning out of the parent if() statement if the condition isn't met rather than continuing down the code. Is my logic completely wrong?
The ifFile() function being called is:
const Upload = require('../../models/Upload');
module.exports = ifFile = async (req, image) => {
const upload = new Upload({
filename: req.files[image][0].filename,
path: req.files[image][0].path,
mimetype: req.files[image][0].mimetype,
size: req.files[image][0].size,
originalname: req.files[image][0].originalname,
});
const newUpload = await upload.save();
return newUpload;
};
Aucun commentaire:
Enregistrer un commentaire