猫鼬错误;无法设置 属性 'x' 为 null

Mongoose Error; Cannot set property 'x' of null

我目前正在使用自定义 sharex 上传基于 nodejs 的服务器, 但是不管我怎么说,都在努力保存从上传到数据库的数据 TypeError: Cannot set property 'X' of null X = 字段之一。 我不明白这是为什么,应用程序可以访问 mongo 数据库,console.log() 提醒我它已连接到数据库。

确认了这一点

但是在处理上传时它就失败了,我完全迷失了,因为我在 Discord Bot 上使用了这个类似的设置没有任何问题,所以我不明白为什么。

有人对我做错了什么有任何解释吗?

上传输出:

{
  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

保存到数据库

 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}`;
        });
    }
});

架构

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);

您正在检查 u 是否为 null,如果是,则尝试为其设置属性。如果 u 为 null,则不能进入 'u.filename = id',因为 u 不存在,您无法为其添加文件名。你需要这样的东西:

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}`;
  });
}