2016-04-12 49 views
1

我有一个向前和向后按钮的图片库。点击任意一个按钮我想插入本地数据库中的一个条目与图像已被查看的时间(所以我可以稍后看到哪个图像已被查看最多)。

这工作完全没有架构:

'click .btn-forward, click .btn-backward' (event, template) { 

    Local.Viewed.upsert({ 
      imageId: this._id 
     }, { 
      $setOnInsert: { 
       imageId: this._id, 
       imageName: this.name 
      }, 
      $inc: { 
       timesViewed: 1 
      } 
     }); 
    } 
}); 

的架构:

Local.Viewed.Schema = new SimpleSchema({ 
    imageId: { 
     type: String 
    }, 
    imageName: { 
     type: String 
    }, 
    timesViewed: { 
     type: Number, 
     defaultValue: 0 
    }, 
    createdAt: { 
     type: Date, 
     autoValue: function() { 
      return new Date(); 
     } 
    } 
}); 

问题:

当我使用这个模式我得到一个错误:

update failed: Error: Times viewed is required at getErrorObject

该架构似乎要求'timesViewed'设置。 我尝试使用“默认值:0”的模式,但不插入0

默认值问题:我怎样才能使架构与此查询兼容?

感谢您的帮助!

莫夫

回答

1

你试过

$setOnInsert: { 
    imageId: this._id, 
    imageName: this.name, 
    timesViewed: 0 
}, 
+1

刚刚看到你的帖子前传,如果没有工作,这听起来像一个错误。 'timesViewed'只能在插入时设置,之后只需增加一次就可以了。你是否已经在mongo中直接查询了查询的行为:你需要''updatesert'用'updatesert' – MrE

0

好吧,我打得四处少许根据您的建议和以前的线程,该解决方案的工作无差错和预期的结果:

架构:

Data = {}; 
Data.Viewed = new Mongo.Collection("dataViewed", {}); 
Data.Viewed.Schema = new SimpleSchema({ 
    imageId: { 
     type: String 
    }, 
    userId: { 
     type: String, 
     autoValue: function() { 
      return this.userId; 
     } 
    }, 
    imageName: { 
     type: String 
    }, 
    timesViewed: { 
     type: Number 
    }, 
    createdAt: { 
     type: Date, 
     autoValue: function() { 
      return new Date(); 
     } 
    } 
}); 
Data.Viewed.attachSchema(Data.Viewed.Schema); 

方法:

Meteor.methods({ 
    dataViewed(obj) { 
     Data.Viewed.upsert({ 
      imageId: obj._id, 
      userId: this.userId 
     }, { 
      $setOnInsert: { 
       imageId: obj._id, 
       userId: this.userId, 
       imageName: obj.term, 
       timesViewed: 0 
      }, 
      $inc: { 
       timesViewed: 1 
      } 
     }); 
    } 
}); 

我认为问题在于我在Schema中为'timesViewed'定义了一个defaultValue/autoValue。 此外,架构中提到的每个属性都必须在$ set或$ setOninsert命令中提及。

感谢您的帮助!