Cannot update db with multer and mongose
I have figured out. Use multer with multer-gridfs-storage and grid-fs-stream to read/write photos into the db.
Create a middlewares folder and add these lines of code:
const multer = require("multer");const {GridFsStorage} = require("multer-gridfs-storage");const storage = new GridFsStorage({ url: process.env.CONNECTION_URL, options: { useNewUrlParser: true, useUnifiedTopology: true }, file: (req, file) => { const match = ["image/png", "image/jpeg"]; if (match.indexOf(file.mimetype) === -1) { const filename = `${Date.now()}-any-name-${file.originalname}`; return filename; } return { bucketName: "photos", filename: `${Date.now()}-any-name-${file.originalname}`, }; },});module.exports = multer({ storage });
Wherever you are posting the data.
Add this piece of middleware after requiring it:
upload.single('profile_photo')
Grid fs stream allows us to read/write into the collections.
If you want to give your collection a name:
let gfs;const conn = mongoose.connection;conn.once("open", function () { gfs = Grid(conn.db, mongoose.mongo); gfs.collection("photos");});
Yup, that's it. You have successfully learned to write alphabets!
External links (please refer to these links in the order if you are serious).
Complete reference for beginners
For advanced usage: