使用collectionfs更新图像

时间:2015-04-06 20:38:05

标签: node.js mongodb meteor

我正在使用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,我已经阅读了流星文档,但无法找到如何做到这一点。任何人都可以建议一种方法或一些文档,我可以学习如何做到这一点?

提前致谢!

2 个答案:

答案 0 :(得分:2)

无法使用FSCollection更新当前网址图片(在本例中为图片),请检查this Github Issue,其中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")
        }                
   }
})

答案 1 :(得分:0)

  

是Imagess.update(currentUserId,{$ set:newFile,function(err,fileObj)?

不。


Meteor的Mongo集合更新语句的语法是在that of mongo Shell's之后建模的。在这种情况下,如果要进行更新,则需要在第一个参数中指定要更新的记录。

Imagess.update({_id:theImageId},newFile);

在mongo中,更新实际上只是覆盖。

这会将Imagess中满足语句_id:theImageId的记录覆盖到新的JSON对象newFile中。但你确定这就是你想要的吗?如果您希望能够更改用户的图像,则此语句已为您完成:

Meteor.users.update(currentUserId, {$set: imagesURL});

如果这真的是你想要的,那么你必须以某种方式获得你想要首先更新的Imagess数据记录(或其任何属性)的id。

注意:insert语句返回插入数据记录的id。