英文:
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}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论