mgo $inc 更新不起作用。

huangapple go评论115阅读模式
英文:

mgo $inc update not working

问题

尝试在每次访问特定博客时更新视图计数:

  1. type Blog struct {
  2. ID bson.ObjectId `bson:"_id,omitempty"`
  3. Topic string
  4. TimeCreated string
  5. Views int
  6. Sections []Section
  7. }
  8. type Section struct {
  9. Name string
  10. Content string
  11. }
  12. func Blogs(w http.ResponseWriter, r *http.Request) {
  13. id := r.FormValue("id")
  14. if id != "" {
  15. blog := model.Blog{}
  16. colQuerier := bson.M{"_id": bson.ObjectIdHex(id)}
  17. e := mCollection.Find(colQuerier).One(&blog)
  18. if e != nil {
  19. console.PrintError(e)
  20. return
  21. }
  22. views := blog.Views
  23. fmt.Println(views)
  24. change := bson.M{"$inc": bson.M{"Views": 1}}
  25. e = mCollection.Update(colQuerier, change)
  26. if e != nil {
  27. console.PrintError(e)
  28. }
  29. jsonData, _ := json.Marshal(blog)
  30. fmt.Fprintf(w, string(jsonData))
  31. }
  32. }

这段代码获取内容,但不会增加视图计数。

英文:

Am trying to update the view count each time a particular blog is visited

  1. type Blog struct {
  2. ID bson.ObjectId `bson:"_id,omitempty"`
  3. Topic string
  4. TimeCreated string
  5. Views int
  6. Sections []Section
  7. }
  8. type Section struct {
  9. Name string
  10. Content string
  11. }

and contoller

  1. func Blogs(w http.ResponseWriter, r *http.Request) {
  2. id := r.FormValue("id")
  3. if id != "" {
  4. blog := model.Blog{}
  5. colQuerier := bson.M{"_id": bson.ObjectIdHex(id)}
  6. e := mCollection.Find(colQuerier).One(&blog)
  7. if e != nil {
  8. console.PrintError(e)
  9. return
  10. }
  11. views := blog.Views
  12. fmt.Println(views)
  13. change := bson.M{"$inc": bson.M{"Views": 1}}
  14. e = mCollection.Update(colQuerier, change)
  15. if e != nil {
  16. console.PrintError(e)
  17. }
  18. jsonData, _ := json.Marshal(blog)
  19. fmt.Fprintf(w, string(jsonData))
  20. }
  21. }

//console is an internal package

the code fetches the content but doesn't increment the Views

答案1

得分: 2

我找到了答案,即使模型中有'Views',但在集合中它是'views',所以它一直在增加'Views',但由于golang正在寻找'views',所以它从未显示出来。

所以正确的代码是

change := bson.M{"$inc": bson.M{"views": 1}}

英文:

I found the answer,
so even though the model had 'Views'. In the collection it was 'views' so it kept incrementing the 'Views', which never showed up because golang was looking for 'views'.

so the working code is

change := bson.M{"$inc": bson.M{"views": 1}}

huangapple
  • 本文由 发表于 2017年1月8日 21:32:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/41533245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定