使用CollectionFS更新图像

3

我正在使用CollectionFS上传图片,但问题是我希望我的用户只能上传一张图片并随后更改它(上传新的图片)。

我已经实现了检查是否已经上传了一张图片的部分。但问题是我无法更改已经存在于数据库中的图片,以下是我用于插入新图片的代码:

'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});
      }
    });
 });

我不知道如何将Imagess.insert更改为Imagess.update,我已经阅读了Meteor文档,但找不到如何操作的方法。是否有人能提供一种方法或一些文档,让我学会如何做呢?

谢谢!


说到不理解如何update,你刚刚不是写了一个更新语句Meteor.users.update(currentUserId, {$set: imagesURL});吗?你能更具体地说明你想做什么吗?如果Imagess是一个mongo集合,你可以像对Meteor.users所做的那样做同样的事情。 - Archy Will He 何魏奇
我对update语句有基本的理解。我想要做的是更新图像,那么Imagess.update(currentUserId, {$set: newFile, function(err,fileObj)是否可以呢? - Esteban89
2个回答

2

使用FSCollection无法更新当前URL图像(在此情况下为图像),请查看此Github问题,其中Raix和Aldeed讨论了一些未来的工作,例如FS.File.updateData(),但尚未实现。

一个可能的解决方法是这样的。

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")
        }                
   }
})

0
这与编程有关,翻译如下:
“Imagess.update(currentUserId, {$set: newFile, function(err,fileObj)?” 这行代码是错误的。
“不对。”
Meteor的Mongo集合更新语句语法是基于 mongo Shell的语法模型设计的。在这种情况下,如果您想要进行更新操作,您需要在第一个参数中指定要更新的记录。
Imagess.update({_id:theImageId},newFile);

在Mongo中,更新实际上就是覆盖。
这将把满足语句“_id:theImageId”的Imagess中的记录覆盖为一个新的JSON对象newFile。但您确定这正是您想要的吗?如果您想更改用户的图像,那么该语句已经为您完成了此操作:
Meteor.users.update(currentUserId, {$set: imagesURL});

如果这确实是你想要的,那么你首先需要以某种方式获取你想要更新的Imagess数据记录的id(或其任何属性)。
注意:insert语句返回插入的数据记录的id。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接