简体   繁体   中英

Attach metadata infos to a Gridfs document file via req.query in API - Node.js Expresss.js MongoDB Multer Gridfs stream

I'm struggling to attach metadata infos to a dfile before actually store it in mongoDB. I'm using:

const express = require("express");
const router = express.Router();
//File managing with gridfs
const mongoose = require('mongoose');
const path = require('path');
const crypto = require('crypto');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const fs = require('fs');

As libraries, and then for the store engine :

const conn = mongoose.createConnection(mongoURI);
//TODO : test the api for the files
let gfs;

conn.once('open', () => {
  // Init stream
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('uploads');
});

// Create storage engine
const storage = new GridFsStorage({
    url: mongoURI,
    gfs:gfs,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
          crypto.randomBytes(16, (err, buf) => {
            if (err) {
              return reject(err);
            }
            const filename = buf.toString('hex') + path.extname(file.originalname);
            const fileInfo = {
              filename: filename,
              bucketName: 'uploads'
            };
            resolve(fileInfo);
          });
        });
    },
    metadata: (req, file, cb) => {
        const metadata = {
            originalname: file.originalname,
            // get this information somehow
            restaurantID :req.query.restaurantID,
            category : req.query.category
        };
        cb(null, metadata);
    }
});
const upload = multer({ storage: storage });

Then for the post API i dont have that much yet just a code to update another mongoDB document with a reference to the file that works

router.post('/upload', upload.single("file"), (req, res) => {

//All the code to update
}

What I need is a way to store infos passed in req.query and put it into the metadata of the gridFS file collection in order to make some query to find the right files in the future and then save it obviusoly. This for every file that I upload with this API. Thank you guys.

I am using this code to add some information to the metadata of the fs.files collection.

state.storage = multerGridfs({
    url: mongoServerUrl,
    db: db.connection,
    file: (req, file) => {
      logger.info(`Uploading file: ${file.originalname} for account ${req.params.accountId}`);
      return {
        filename: file.originalname,
        metadata: { accountId: req.params.accountId}
      };
    },
  });

As you can see to use the metadata you return it as a property of the object you returned in the file: section.

Mongo Compass条目以添加文件

Here is a link with some good examples https://www.npmjs.com/package/multer-gridfs-storage .

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM