0

I can upload a file to my MongoDB using multer-gridfs-storage, but I am having trouble associating the file with my "customer" schema. Basically, each customer should have three types of files: Network, email, and password files. Each file will be a .txt. My end goal is to have a show page for each customer and be able find the customer by :id and then populate the customer's three files.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const customerSchema = new Schema({
    name: {
        type: String
          },
    address: {
        street: String,
        city: String,
        state: String,
        zip: String,
    },
    fileID:
        {
            type: Schema.Types.ObjectId,

        }

}, { timestamps: true });


module.exports = mongoose.model("Customer", customerSchema);



// Create mongo connection
const conn = mongoose.createConnection(process.env.MONGO_DB_URL);

// Init gfs
let gfs;

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

// Create storage engine
const storage = new GridFsStorage({
  url: process.env.MONGO_DB_URL,
  file: (req, file) => {
        return {
        filename: file.originalname,
        bucketName: 'customers'
        };


  }
});
const upload = multer({ storage });



post route to upload files

router.post('/upload', upload.single('file'), (req, res) => {
    res.json({ file: req.file });
  });
Blakesq
  • 1
  • 1
  • welcome to Stack Overflow! this is a good start at a question; please include details on what part of what you are attempting *is* working, what part *isn't* working, expected output vs. actual output and any error messages and such you are receiving; thanks! – landru27 Jun 27 '19 at 02:31

1 Answers1

1

Have three fields in your Customer model for the three types of files. Save the files to different collections using gridfs-storage and then store the id of these uploaded files to the corresponding field in your model. This way you can keep different collections of different type of files.

Chinmay Goyal
  • 23
  • 1
  • 6