How do i add new field other than multer-gridfs-storage default properties

末鹿安然 提交于 2019-12-08 13:22:22

问题


I wanted to add new fields (objects) other than multer-gridfs-storage default fields but to no avail, the fields i want to add are:

  • Description
  • category
  • Token

The default field has something like

  • _id
  • length
  • chunksize
  • uploadDate
  • md5
  • contentType

instead want to add something like

  • _id
  • length
  • chunksize
  • uploadDate
  • md5
  • contentType
  • description
  • category and the rest

And also is there a way to add a thumbnail to file so i don't i have reference my file id to the thumbnail in other collection

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) => {
    
    
    res.redirect('/upload/files')


});

回答1:


Those properties are populated by multer and further enhanced by whatever storage engine you are using, in this case multer-gridfs-storage when the file is stored. You won't be able to manipulate those yourself because they are generated when the file is parsed in the request and then when it is stored in the database.

Instead of using metadata to store your business logic you should use a framework like mongoose and store that information on a collection and use an id field to get a link to your file. Something like this

const Movie = mongoose.model('Movie', { 
    description: String,
    category: String,
    token: String,
    fileId: Schema.Types.ObjectId
});

Read your fields from the body and save them using this collection to the database and use the autogenerated _id of your file as the fileId. This way you can easily query your data and still have a handle to the file available.



来源:https://stackoverflow.com/questions/53548990/how-do-i-add-new-field-other-than-multer-gridfs-storage-default-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!