我尝试在每次访问特定博客时更新浏览次数
type Blog struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Topic string
TimeCreated string
Views int
Sections []Section
}
type Section struct {
Name string
Content string
}
和 Controller
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是一个内部包
代码获取内容但不增加 View
最佳答案
我找到了答案, 所以即使模型有“ View ”。在集合中它是“ View ”,因此它不断增加“ View ”,但它从未出现,因为 golang 正在寻找“ View ”。
所以工作代码是
change := bson.M{"$inc": bson.M{"views": 1}}
关于go - mgo $inc 更新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41533245/