MongoDB GridFSBucket поток загрузки не возвращает длину потока изображений base64 - PullRequest
0 голосов
/ 28 апреля 2020

Я выполняю рефакторинг кода своей команды, чтобы удалить Предупреждения об устаревании из MongoDB.

Я удалил библиотеку gridfs-stream и вместо нее * 1008 использую GridFSBucket *

Но есть проблема: поток загрузки с использованием GridFSBucket не возвращает длину изображения base64, а возвращает 0. Это прерывает один из тестов в нашем коде .


Это код, использующий GridFSBucket:

function getGrid() {
  return new mongoose.mongo.GridFSBucket(conn.db);
}

module.exports.store = function(id, contentType, metadata, stream, options, callback) {

  ... // unrelated things

  var strMongoId = mongoId.toHexString(); // http://stackoverflow.com/a/27176168
  var opts = {
    contentType: contentType,
    metadata: metadata
  };

  options = options || {};

  if (options.filename) {
    opts.filename = options.filename;
  }

  if (options.chunk_size) {
    var size = parseInt(options.chunk_size, 10);
    if (!isNaN(size) && size > 0 && size < 255) {
      opts.chunkSizeBytes = chunk_size * size;
    }
  }

  var gfs = getGrid();
  var writeStream = gfs.openUploadStreamWithId(strMongoId, opts.filename, opts);

  writeStream.on('finish', function(file) {
    console.log(file) // <== Notice the log for this line below
    return callback(null, file);
  });

  writeStream.on('error', function(err) {
    return callback(err);
  });

  stream.pipe(writeStream);
};

Результат для console.log(file):

{
    "_id": "5ea7a3ffbc7dd36e7df4561e",
    "length": 0, // <== Notice length is 0 here
    "chunkSize": 10240,
    "uploadDate": "2020-04-28T03:33:19.734Z",
    "filename": "default_profile.png",
    "md5": "d41d8cd98f00b204e9800998ecf8427e",
    "contentType": "image/png",
    "metadata": {
        "name": "default_profile.png",
        "creator": {
            "objectType": "user",
            "id": "5ea7a3febc7dd36e7df4560a"
        }
    }
}

Это старый код, использующий gridfs-stream:

var Grid = require('gridfs-stream');
...

function getGrid() {
  return new Grid(mongoose.connection.db, mongoose.mongo);
}

module.exports.store = function(id, contentType, metadata, stream, options, callback) {

  ... // unrelated things

  var strMongoId = mongoId.toHexString(); // http://stackoverflow.com/a/27176168
  var opts = {
    _id: strMongoId,
    mode: 'w',
    content_type: contentType
  };

  options = options || {};

  if (options.filename) {
    opts.filename = options.filename;
  }

  if (options.chunk_size) {
    var size = parseInt(options.chunk_size, 10);
    if (!isNaN(size) && size > 0 && size < 255) {
      opts.chunk_size = chunk_size * size;
    }
  }

  opts.metadata = metadata;

  var gfs = getGrid();
  var writeStream = gfs.createWriteStream(opts);

  writeStream.on('close', function(file) {
    console.log(file) // <== Notice the log for this line below
    return callback(null, file);
  });

  writeStream.on('error', function(err) {
    return callback(err);
  });

  stream.pipe(writeStream);
};

И вот результат console.log(file):

{
    "_id": "5ea7a43a5d6eea73e0a3c8b1",
    "filename": "default_profile.png",
    "contentType": "image/png",
    "length": 634, // <== We have the length here
    "chunkSize": 10240,
    "uploadDate": "2020-04-28T03:34:18.069Z",
    "metadata": {
        "name": "default_profile.png",
        "creator": {
            "objectType": "user",
            "id": "5ea7a4395d6eea73e0a3c89d"
        }
    },
    "md5": "c37659eb6a9e741656a8d0348765c668"
}

Итак, как я могу получить длину, используя GridFSBucket? Спасибо!


ОБНОВЛЕНИЕ :

Это журнал переменной stream в обоих случаях:

{
    "contentType": "image/png",
    "fileName": "default_profile.png",
    "transferEncoding": "base64",
    "contentDisposition": "attachment",
    "generatedFileName": "default_profile.png",
    "contentId": "216d9aab57544410901f8ba7981e63aa@mailparser",
    "stream": {
        "_events": {},
        "_eventsCount": 0,
        "writable": true,
        "checksum": {
            "_handle": {},
            "writable": true,
            "readable": true
        },
        "length": 0,
        "current": ""
    }
}
...