2016-04-12 48 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命令中提及。

感謝您的幫助!