Multer gridfs存储将上载的文件引用到新集合

时间:2018-11-30 13:39:26

标签: node.js mongoose-schema multer multer-gridfs-storage

使用multer gridfs存储上传的文件,我想将其引用到新创建的收藏集(电影)。 我引用的已上传文件的fileID与已上传文件不同,即使电影收藏没有保存到数据库中也是如此。 即使电影收藏未保存在数据库中,我引用的已上传文件的fileID与上载文件也不相同

//movie schema
    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;

    const MovieSchema = new Schema({
    	description: {
    		type: String,
    	},
    	category: {
    		type: String,
    	},
    	token: {
    		type: String,
    	},
    	fileID: {
    		type: Schema.Types.ObjectId,
    		ref: "contents.files"
    	}
    });

    module.exports = movies = mongoose.model('movies', MovieSchema);



    let gfs;

    conn.once('open', () => {
        gfs = Grid(conn.db, mongoose.mongo);
        gfs.collection('contents');

    });



    const storage = new GridFsStorage({
        url: config.db,
        file: (req, file) => {
            return new Promise((resolve, reject) => {
            
                    const filename = req.body.fileName + path.extname(file.originalname);
                    const Description = req.body.Description
                    const fileInfo = {
                        filename: filename,
                        bucketName: 'contents',
                        metadata: req.body,
                        
                    }
                    resolve(fileInfo, Description);
                
            });
        }
    });
    const   upload = multer({
        storage
    });
    router.get('/', (req, res) => {
        res.render('index');
        console.log(req.body)
    });

    //** uploading file to the db */

    router.post('/', upload.any(), (req, res) => {
        
          
        const movie = new movies({
            description: "test",
            category: "test",
            fileID: gfs.files.id
        })
        
          movie.save()
    });

fileID与上载的文件ID不同,并且集合没有保存在DB上。fileID与上载的文件ID不同,并且集合也没有保存在DB上。fileID与上载的文件ID也不同。集合未保存在数据库中

1 个答案:

答案 0 :(得分:2)

它不起作用,因为您使它变得比所需的更加复杂。文件中的引用是不必要的。您可以使用此代码完成相同的操作。

//movie schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MovieSchema = new Schema({
  description: {
    type: String,
  },
  category: {
    type: String,
  },
  token: {
    type: String,
  },
  fileID: {
    type: Schema.Types.ObjectId, // There is no need to create references here
  }
});

module.exports = movies = mongoose.model('movies', MovieSchema);

const storage = new GridFsStorage({
  url: config.db,
  file: (req, file) => {
    return new Promise((resolve, reject) => {  
      // if you are using a separate collection to store data 
      // there is no need to save this information on the metadata
      // because you'll probably never use it
      const filename = req.body.fileName + path.extname(file.originalname);
      const fileInfo = {
        filename: filename,
        bucketName: 'contents'
      }
      resolve(fileInfo);
    });
  }
});
const upload = multer({
  storage
});

router.get('/', (req, res) => {
  res.render('index');
  console.log(req.body)
});

//** uploading file to the db */
router.post('/', upload.any(), (req, res) => {
  const movie = new movies({
    description: req.body.Description,
    category: req.body.Category,
    // Grab the file id that was stored in the database by the storage engine as the reference to your file
    fileID: req.file._id
  })

  movie.save()
});

您不应使用uploads.any()。这将接受任何传入的文件。取而代之的是,您应该使用arraysinglefields,具体取决于您发送了多少文件以及用于发送文件的字段名称。

要稍后再从数据库中读取该文件,您只需查询Movies集合,并且fileId字段具有一个标识符,您可以将其传递给openDownloadStream中的GridfsBucket并将其流传输到响应,从而将使用该ID存储的文件返回给用户,或将其用于您的应用程序具有的任何业务逻辑中。