mgo $inc update not working

1.3k views Asked by At

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

There are 1 answers

1
Shiva Kishore On BEST ANSWER

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}}