Sunday, 23 April 2017

How to add image path in user profile using multer-gridfs-storage ,express, mongodb

below is my file upload code

/** Setting up storage using multer-gridfs-storage */
    var storage = GridFsStorage({
        gfs : gfs,
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
        },
        /** With gridfs we can store aditional meta-data along with the file */
        metadata: function(req, file, cb) {
            cb(null, { originalname: file.originalname });
        },
        root: 'ctFiles' //root name for collection to store files into
    });

    var upload = multer({ //multer settings for single upload
        storage: storage
    }).single('file');

    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            console.log(res.file);
            console.log(res[0].file);
             res.json({error_code:0,err_desc:null});
        });
    });

i want to store user name, email and file path in user collection this is my UserSchema

var UserSchema = new Schema({
    name: String,
    email: {
        type: String,
        lowercase: true
    },
    filepath: String,
});

this is how image has stored in collection

{
        "_id" : ObjectId("58fb894111387b23a0bf2ccc"),
        "filename" : "file-1492879681306.PNG",
        "contentType" : "image/png",
        "length" : 67794,
        "chunkSize" : 261120,
        "uploadDate" : ISODate("2017-04-22T16:48:01.350Z"),
        "aliases" : null,
        "metadata" : {
                "originalname" : "Front.PNG"
        },
        "md5" : "404787a5534d0479bd55b2793f2a74b5"
}

this is my expectation result: in user collection i should get data like this

{ 

        "name" :"asdf", 
        "email" : "asdf@gmail.com", 
        "filepath":"file/file-1492879681306.PNG"

    }



via its me

No comments:

Post a Comment