node.js - Multer gridfs存储引用上传的文件到新集合

标签 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 不同,且集合未保存在数据库中 文件 ID 与上传的文件 Id 不同,且集合未保存在数据库中 文件 ID 与上传的文件 Id 不同,且集合未保存在数据库中

最佳答案

它不起作用,因为你让事情变得比需要的更复杂。文件中的引用是不必要的。您可以使用此代码完成相同的任务。

//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()。这将接受任何传入的文件。相反,您应该使用 array , singlefields取决于您发送的文件数量以及用于发送这些文件的字段名称。

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

关于node.js - Multer gridfs存储引用上传的文件到新集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53558684/

相关文章:

node.js - 如何在后路由中将字符串数组分配给 Mongoose 模型的定义

node.js - 一个字段在 Mongoose 模式中可以有哪些选项?

javascript - 在可以从 promise 中收集结果之前响应终止

javascript - Mongoose 架构 : Forcing an array of objects to be created

html - 无法将 View 添加为 html 页面 (sails.js)

node.js - Mongoose ,从数组中删除一个对象并更新其他对象

angularjs - Amazon S3,GET 请求被禁止?

node.js - 使用 Node.js 从 Postman 发送数据时出现错误

node.js - 在 NodeJs 中使用 Multer 上传文件时出错

mysql - 向 Node 表达mysql同步问题的多个请求