如何将文件上传到mongodb GridFs?

o3imoua4  于 2023-05-22  发布在  Go
关注(0)|答案(1)|浏览(140)

我正在使用mongodb版本4.2.8,我试图将在服务器上创建的PDF保存到mongofiles,而不实现任何其他第三方软件包(mongoose,multer等)。我的代码的问题是我不知道如何要求Grid函数。下面只是我正在编写的代码的一个示例。

const mongo = require('mongodb').MongoClient;
  const Grid = require('mongodb').GridFSBucket; // cant figure out how it works.
  // const Grid = require('mongodb').Grid; // not a function
  mongo.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, async (err, client) => {
  if (err) {
    console.error(err);
    return;
  }
  var db = client.db('brickfy')
  var grid = new Grid(client, 'fs');
  var writestream = grid.createWriteStream({
    metadata:{category:'example' user:'user'},
    content_type:'application/pdf',
    filename: '/path/my-pdf'
  });
  writestream.on('close', function (file) {
    console.log(file);
  }

});

我试着用这个例子来学习:https://mongodb.github.io/node-mongodb-native/api-generated/grid.html,但不是使用新的Buffer上传图像。我在互联网上找到的其他例子是使用mongoose和grid-fs-stream。这是一个使用所有工具的示例,我不想安装https://data-flair.training/blogs/mongodb-gridfs-tutorial/

qacovj5a

qacovj5a1#

下面的代码是:

const mongo = require('mongodb');
const mongoClient = new mongo.MongoClient(URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

mongo.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, async (err, client) => {
  if (err) {
    console.error(err);
    return;
  }
  function uploadFileToMongo (){
   DEF.mongo.gridfsUploadStream = async function(file, bucketName, metadata, filetype, id = undefined, malwareChecks = true) {
    // this function bypasses the need to save the file
    // before uploading to the database
    let bucket = new mongo.GridFSBucket(DEF.db, { bucketName: bucketName });
    const stream_opts = { metadata: metadata, contentType: filetype };
    
    let uploadStream = undefined;
    uploadStream = bucket.openUploadStreamWithId(id, file.filename, stream_opts);

    try {
      await function() {
        return new Promise((resolve, reject) => {
          file.pipe(uploadStream)
            .on('finish', resolve)
            .on('error', reject);
        });
      }();
      return { ok: true };
    } catch (e) {
      console.error(e, 'upload-500');
    }
  };
  }
});

相关问题