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 });
});