I'm currently working a custom sharex uploading nodejs-based server,
But struggling with saving the data from the upload to the database, no matter what I try it says
TypeError: Cannot set property 'X' of null
X = one of the fields.
I don't understand why this is, the application has access to the mongo database, that is confirmed by a console.log()
alerting me that it has connected to the database.
But on processing the upload it just fails, and I am completely lost on this as I have use this similar set up on a Discord Bot with no issues, so I don't understand why.
Does anyone have any explanation as to what I am doing wrong?
Output on Upload:
{
name: 'ShareX_3oFMZJeV2S.png',
data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 01 85 00 00 01 2a 08 06 00 00 00 fa 69 4c 73 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... 14082 more bytes>,
size: 14132,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/png',
md5: 'b70962199714328ed2a889b2fc211671',
mv: [Function: mv]
}
W8LOR5q png
null
Save to DB
console.log(req.files.file)
let data = req.files.file
let hex = randomString(7, false);
let mimeType = extension(data.mimetype)
let buf = data.data;
let id = `${hex}.${mimeType}`;
await upload.findOne({
fileName: id
}, async (err, u) => {
if (err) console.log(err);
if (!u) {
console.log(hex, mimeType)
console.log(u)
u.fileName = id;
u.fileID = hex;
u.fileMimetype = mimeType;
u.fileBuffer = buf;
u.filePrivate = false;
await u.save().then(r => {
return 'test'
}).catch((e) => {
return `ERROR: ${e}`;
});
}
});
Schema
const { Schema, model } = require('mongoose');
const uploadSchema = Schema({
fileName: String,
fileImage: String,
fileID: String,
fileMimetype: String,
filePbuffer: Buffer,
filePrivate: Boolean,
uploadDate: {
type: Date,
default: Date.now
}
});
module.exports = model('upload', uploadSchema);
You're checking if u is null, and if it is, trying to set properties on it. If u is null, you can't go 'u.filename = id'
, because u doesn't exist for you to add a filename to it. You need something like:
if (!u) {
const newObj = {}
newObj.fileName = id;
newObj.fileID = hex;
newObj.fileMimetype = mimeType;
newObj.fileBuffer = buf;
newObj.filePrivate = false;
await newObj.save().then(r => {
return 'test'
}).catch((e) => {
return `ERROR: ${e}`;
});
}