[ad_1]
pls help me 🙁 i am trying to upload pdf files to mongodb using nodejs, express and pug; i tried as much as i can but nothing worked.
here’s my code:
connecting model database to mongodb
fileModel.js
const fileSchema = new mongoose.Schema({
file: {
type: String,
required: [true, 'Must have an uploaded file']
}
used multer and will not use gridfs; i also have an update users profile within this app and its working; but this one doesn’t.
fileController.js
const multerStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public/files');
},
filename: (req, file, cb) => {
const ext = file.mimetype.split("https://stackoverflow.com/")[1];
cb(null, `file-${file.fieldname}-${Date.now()}.${ext}`);
}
});
const multerFilter = (req, file, cb) => {
if (file.mimetype.split("https://stackoverflow.com/")[1] === 'pdf') {
cb(null, true);
} else {
cb(new AppError('Not a PDF File!!', 400), false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter
});
exports.uploadFile = upload.single('file');
exports.createFile = async (req, res) => {
const newFile = await File.create({
file: req.file.filename
});
};
upload-file.js
export const upload = async (data) => {
try {
const res = await axios({
method: 'POST',
enctype: 'multipart/form-data',
url: 'http://127.0.0.1:3000/api/files',
data
});
if (res.data.status === 'success') {
showAlert('success', 'File uploaded successfully!');
window.setTimeout(() => {
location.assign('/documents');
}, 1500);
}
} catch (err) {
showAlert('error', err.response.data.message);
}
};
index.js
const uploadForm = document.querySelector('.form--file');
if (uploadForm)
uploadForm.addEventListener('submit', e => {
e.preventDefault();
const form = new FormData();
form.append('file', document.getElementById('file').files[0]);
upload(form, 'data');
});
add-files.pug
.custom-file.mb-3
label(for="file" class="form-label")
input#file(class="form-control form-control-lg", name="file", type="file")
button.button11.btn.btn-primary.btn-lg(type="submit", value="Submit") CONFIRM
THE ERROR
TypeError Cannot read properties of undefined (reading 'filename')
UNHANDLED REJECTION! Shutting down...
i also tried:
file: req.files.file
but the error that i got is:
ValidationError File validation failed: file: Cast to string failed for value "{
name: 'the-filename.pdf',
data: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 f6 e4 fc df 0a 31 20 30 20 6f 62 6a 0a 3c 3c 0a 2f 54 79 70 65 20 2f 43 61 74 ... 24353172 more bytes>,
size: 2435322,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'application/pdf',
md5: 'a2bb637f0d2b563e0eaf511fde0cd0',
mv: [Function: mv]
}" (type Object) at path "file"
UNHANDLED REJECTION! Shutting down...
so what did i do wrong? :<
[ad_2]