I'm using collectionFS to upload an image, the thing is I want my users to be able to upload just one image and then change it(upload a new one). I have the part in place to check if an image is already uploaded but the thing is I can't change the image that is in the db, this is the code I have to insert a new image:
'change .myFileInput': function(event, template) {
FS.Utility.eachFile(event, function(file) {
var newFile = new FS.File(file);
newFile.metadata = {
createdBy:Meteor.userId(),
}
Imagess.insert(newFile, function (err, fileObj) {
if (err){
// handle error
} else {
// handle success depending what you need to do
var currentUserId = Meteor.userId();
var imagesURL = {
"profile.image": "/cfs/files/images/" + fileObj._id
};
Meteor.users.update(currentUserId, {$set: imagesURL});
}
});
});
I don't know how to change the Imagess.insert to Imagess.update, I have already read the meteor documentation but can't find how to do it. Can anyone suggest a way or some docs where I can learn how to do it?
Thanks in advance!
There is no way to update a current url image using FSCollection(in this case the image), check this Github Issue,where Raix and Aldeed talk about some future work like FS.File.updateData()
, but its not implemented yet.
A posible workaround will be this.
Template.example.events({
'click #changeImage':function(event,template){
var message = confirm("Do you wanna change this image?");
if(message == true){
var file = $('#changeImageInput').get(0).files[0],
newFile = new FS.File(file);
newFile.metadata = {
createdBy:Meteor.userId(),
}
var query = Images.findOne({'metadata.createdBy':Meteor.userId()}) //supposing there is only one image if not use a .fetch() and a for instead.
//removing the current image.
Images.remove({_id:query._id},function(err,result){
//if there is not error removing the image, insert new one with the same metadata
if(!err){
Images.insert(fsFile,function(){
if(!err){
console.log("New image get upload")
}
})
}
});
}else{
console.log("user don't want to change the image")
}
}
})