使用 graphql 将文件上传到 mongodb with mongoose

Uploading files with graphql to mongodb with mongoose

我想使用 graphql 解析器将文件上传到 mongodb。 在 server.js 中,我有这个帮助功能来存储文件,该文件被导出以在我的解析器中使用。 该功能基于我在这里找到的内容:https://github.com/jaydenseric/graphql-upload/issues/8),但现在 graphql 中的某些内容已更改。例如解构文件对象。我不知道应该在路径变量中找到什么以及我应该如何使用这个 createReadStream(从文件中解构的函数)。

const mongoose = require('mongoose');
const Grid = require('gridfs-stream');
const fs = require('fs');

//...

// Connect to Mongo
mongoose
  .connect(process.env.mongoURI, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false
  }) // Adding new mongo url parser
  .then(() => console.log('MongoDB Connected...'))
  .catch(err => console.log(err));




const storeFile = async (upload) => {
   const { filename, createReadStream, mimetype } = await upload.then(result => result);

   const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, { bucketName: 'files' });

   const uploadStream = bucket.openUploadStream(filename, {
     contentType: mimetype
   });
   createReadStream()
     .pipe(uploadStream)
     .on('error', console.log('error'))
     .on('finish', console.log('finish'));
 }

module.exports = { storeFile }
//...

我的解析器(这里是最小版本,因为现在我只想将文件上传到我的数据库中。在我的一次尝试中,它甚至创建了 fs.files 和 fs.chunks 集合,但没有数据):

Mutation: {
    uploadFile: async (_, { file }) => {
      console.log(file);
      const fileId = await storeFile(file);

      return true;
     
    }
  }

我现在遇到这个错误:

Unhandled Rejection (Error): GraphQL error: The "listener" argument must be of type function. Received undefined

并且在终端中我打印了 'error'(就像在 pipe.on('error', console.log('error') 语句中一样)

而且我只能上传小文件(最大 60 kb),所有较大的文件都不会上传,但所有尝试都显示错误。

好的,我设法解决了。

解析器突变:

const { storeFile } = require('../../server');
//...

uploadFile: async (_, { file }) => {
      const fileId = await storeFile(file).then(result => result);

      return true;
// later I will return something more and create some object etc.
    }

来自server.js

的支持函数
 const storeFile = async (upload) => {
    const { filename, createReadStream, mimetype } = await upload.then(result => result);

    const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, { bucketName: 'files' });
    
    const uploadStream = bucket.openUploadStream(filename, {
      contentType: mimetype
    });
    return new Promise((resolve, reject) => {
      createReadStream()
        .pipe(uploadStream)
        .on('error', reject)
        .on('finish', () => {
            resolve(uploadStream.id)
        })
    })
  }

  module.exports = { storeFile }