mgo $inc 更新不起作用。

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

mgo $inc update not working

问题

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

type Blog struct {
    ID          bson.ObjectId `bson:"_id,omitempty"`
    Topic       string
    TimeCreated string
    Views       int
    Sections    []Section
}

type Section struct {
    Name    string
    Content string
}

func Blogs(w http.ResponseWriter, r *http.Request) {
    id := r.FormValue("id")
    if id != "" {
        blog := model.Blog{}
        colQuerier := bson.M{"_id": bson.ObjectIdHex(id)}

        e := mCollection.Find(colQuerier).One(&blog)
        if e != nil {
            console.PrintError(e)
            return
        }

        views := blog.Views
        fmt.Println(views)

        change := bson.M{"$inc": bson.M{"Views": 1}}
        e = mCollection.Update(colQuerier, change)
        if e != nil {
            console.PrintError(e)
        }

        jsonData, _ := json.Marshal(blog)
        fmt.Fprintf(w, string(jsonData))
    }
}

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

英文:

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

type Blog struct {
	ID          bson.ObjectId `bson:"_id,omitempty"`
    Topic       string
    TimeCreated string
    Views       int
    Sections    []Section
}
type Section struct {
    Name    string
    Content string
}

and contoller

func Blogs(w http.ResponseWriter, r *http.Request) {
	id := r.FormValue("id")
    if id != "" {
	    blog := model.Blog{}
	    colQuerier := bson.M{"_id": bson.ObjectIdHex(id)}

	    e := mCollection.Find(colQuerier).One(&blog)
	    if e != nil {
		    console.PrintError(e)
		    return
	    }
	    views := blog.Views
	    fmt.Println(views)
	    change := bson.M{"$inc": bson.M{"Views": 1}}

	    e = mCollection.Update(colQuerier, change)
	    if e != nil {
		    console.PrintError(e)
	    }

	    jsonData, _ := json.Marshal(blog)
	    fmt.Fprintf(w, string(jsonData))
     }
}

//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:

确定