问题
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