I am using formidable to parse an incoming form which contains both text and an uploaded image. However, I am not able update those global variables(name, dexcription..etc) with those parsed values inside the form.parse() method.
If I console.log that newCampground object inside the form.parse() method, every field value is saved properly. But as soon as I console.log the same new Campground object outside of the parse method, it is empty. I have spent 2 hrs trying to fix this but I can't get it to work. Any help will be appreciated!
var name;
var description;
var price;
var image;
var author = {
id: req.user._id,
username: req.user.username
};
var newCampground = {name: name,
image: image,
description: description,
author: author,
price: price,
uploadImage: uploadImage
} ;
var form = formidable.IncomingForm();
form.parse(req, function(err, fields, files){
newCampground["name"] = fields.name;
newCampground.description = fields.description;
newCampground.price = fields.price;
newCampground.image = fields.image;
console.log("Inside of parsed method);
console.log(JSON.stringify({newCampground}));//this one has everything
});
console.log("Outside of parsed method);
console.log(JSON.stringify({newCampground}));//nothing inside
// ===============console output==================//
Outside of parsed method
{"newCampground":{"author":{"id":"5ab8893a4dd21b478f8d4c40","username":"jun"}}}
Inside of parsed method
{"newCampground":{"name":"aaaaa","image":"","description":"ddddd","author":{"id":"5ab8893a4dd21b478f8d4c40","username":"jun"},"price":"vvvvv","uploadImage":"/uploads/i.jpg"}}
{ author: { id: 5ab8893a4dd21b478f8d4c40, username: 'jun' },
comments: [],
_id: 5ac4164432f6902a2178e877,
__v: 0 }