How to add images in MongoDB using Mongoose (without GridFS)

How to add images in MongoDB using Mongoose (without GridFS)

Accessing images from server side and storing in MongoDB is the easiest thing, if you do it right.

In your Node.js application, simply write the command: npm i express-fileupload

Your server.js should look something like this:

const app = express()
const fu = require("express-fileupload")
app.use(fu())
app.set("view engine","ejs")

We will now create a GET and a POST route:-

app.get("/home", (req,res)=>{
    res.render("home")
})
app.post("/save",async(req,res)=>{
    let ss = req.files.dp
    if(ss.mimetype == "image/jpeg" ||ss.mimetype == "image/png" || ss.mimetype == "image/jpg" ){
        let s = req.files.dp.data

        let base64 = s.toString('base64');
       //  console.log(base64.substr(0,200));
         image = Buffer.from(base64, 'base64');
let doc = await usermodel.findOneAndUpdate({email:req.cookies['email']},{
      $set:{
        dp:{ data: image,
          contentType: ss.mimetype},
        name:req.body.name,

      }
    })   
 }
})

Create a home.ejs file with the following form:

 <form id="form" method="POST" action="/save" enctype="multipart/form-data">

     <label>Name label><input  type="text" name="name" id="name"><br>
       <label>Profile picture label><input type="file"  id="dp" name="dp">
  </form>

Don't forget to set the enctype as "multipart/form-data" in the form, as without that it won't work.

Schema of the collection:

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

const UserSchema = new Schema({

    dp: {
        data:{type:Buffer},
        contentType:{type:String},

    },

    name:{type:String},

})

module.exports = mongoose.model('User', UserSchema);

That's all!

You can also set a size limit to the file being uploaded by using body-parser. Just add the two lines below:

app.use(bodyParser.json({ limit: "50mb" }))
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }))