当前位置: 首页>>代码示例>>Golang>>正文


Golang bson.ObjectIdHex函数代码示例

本文整理汇总了Golang中gopkg/in/mgo/v2/bson.ObjectIdHex函数的典型用法代码示例。如果您正苦于以下问题:Golang ObjectIdHex函数的具体用法?Golang ObjectIdHex怎么用?Golang ObjectIdHex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ObjectIdHex函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: AddOrUpdateTag

// 添加或更新标签, 先查下是否存在, 不存在则添加, 存在则更新
// 都要统计下tag的note数
// 什么时候调用? 笔记添加Tag, 删除Tag时
// 删除note时, 都可以调用
// 万能
func (this *TagService) AddOrUpdateTag(userId string, tag string) info.NoteTag {
	userIdO := bson.ObjectIdHex(userId)
	noteTag := info.NoteTag{}
	db.GetByQ(db.NoteTags, bson.M{"UserId": userIdO, "Tag": tag}, &noteTag)

	// 存在, 则更新之
	if noteTag.TagId != "" {
		// 统计note数
		count := noteService.CountNoteByTag(userId, tag)
		noteTag.Count = count
		noteTag.UpdatedTime = time.Now()
		//		noteTag.Usn = userService.IncrUsn(userId), 更新count而已
		db.UpdateByIdAndUserId(db.NoteTags, noteTag.TagId.Hex(), userId, noteTag)
		return noteTag
	}

	// 不存在, 则创建之
	noteTag.TagId = bson.NewObjectId()
	noteTag.Count = 1
	noteTag.Tag = tag
	noteTag.UserId = bson.ObjectIdHex(userId)
	noteTag.CreatedTime = time.Now()
	noteTag.UpdatedTime = noteTag.CreatedTime
	noteTag.Usn = userService.IncrUsn(userId)
	noteTag.IsDeleted = false
	db.Insert(db.NoteTags, noteTag)

	return noteTag
}
开发者ID:nosqldb,项目名称:zhujian,代码行数:34,代码来源:TagService.go

示例2: GetNotebookShareGroups

// 得到笔记本分享给的groups
func (this *ShareService) GetNotebookShareGroups(notebookId, userId string) []info.ShareNotebook {
	// 得到分组s
	groups := groupService.GetGroups(userId)

	// 得到有分享的分组
	shares := []info.ShareNotebook{}
	db.ListByQ(db.ShareNotebooks,
		bson.M{"NotebookId": bson.ObjectIdHex(notebookId), "UserId": bson.ObjectIdHex(userId), "ToGroupId": bson.M{"$exists": true}}, &shares)
	mapShares := map[bson.ObjectId]info.ShareNotebook{}
	for _, share := range shares {
		mapShares[share.ToGroupId] = share
	}
	LogJ(shares)

	// 所有的groups都有share, 但没有share的group没有shareId
	shares2 := make([]info.ShareNotebook, len(groups))
	for i, group := range groups {
		share, ok := mapShares[group.GroupId]
		if !ok {
			share = info.ShareNotebook{}
		}
		share.ToGroup = group
		shares2[i] = share
	}

	return shares2
}
开发者ID:sunyinhuiCoding,项目名称:leanote,代码行数:28,代码来源:ShareService.go

示例3: HandlerId

func HandlerId(response http.ResponseWriter, request *http.Request) {
	fmt.Println(request.Method)
	fmt.Println("Entrou no handlerId")

	switch request.Method {
	case "GET":
		vars := mux.Vars(request)
		id := bson.ObjectIdHex(vars["id"])

		prova := GetProva(id)
		fmt.Println(prova)
		js, _ := json.MarshalIndent(prova, " ", "   ")
		response.Write(js)

	case "POST":
		var prova Prova
		json.NewDecoder(request.Body).Decode(&prova)
		fmt.Println("prova.Id")
		if prova.Id == "" {
			err := Insere(&prova)
			fmt.Println(err)
		} else {
			err := Update(&prova)
			fmt.Println(err)
		}

	case "DELETE":
		vars := mux.Vars(request)
		id := bson.ObjectIdHex(vars["id"])
		err := Delete(id)
		fmt.Println(err)
	}
}
开发者ID:GrupoEstudoMega,项目名称:MegaRunning,代码行数:33,代码来源:prova.go

示例4: LikeBlog

// 点赞
// retun ok , isLike
func (this *BlogService) LikeBlog(noteId, userId string) (ok bool, isLike bool) {
	ok = false
	isLike = false
	if noteId == "" || userId == "" {
		return
	}
	// 判断是否点过赞, 如果点过那么取消点赞
	note := noteService.GetNoteById(noteId)
	if !note.IsBlog /*|| note.UserId.Hex() == userId */ {
		return
	}

	noteIdO := bson.ObjectIdHex(noteId)
	userIdO := bson.ObjectIdHex(userId)
	var n int
	if !db.Has(db.BlogLikes, bson.M{"NoteId": noteIdO, "UserId": userIdO}) {
		n = 1
		// 添加之
		db.Insert(db.BlogLikes, info.BlogLike{LikeId: bson.NewObjectId(), NoteId: noteIdO, UserId: userIdO, CreatedTime: time.Now()})
		isLike = true
	} else {
		// 已点过, 那么删除之
		n = -1
		db.Delete(db.BlogLikes, bson.M{"NoteId": noteIdO, "UserId": userIdO})
		isLike = false
	}
	ok = db.Update(db.Notes, bson.M{"_id": noteIdO}, bson.M{"$inc": bson.M{"LikeNum": n}})

	return
}
开发者ID:ZypcGroup,项目名称:leanote,代码行数:32,代码来源:BlogService.go

示例5: HasUpdatePerm

// updatedUserId是否有修改userId noteId的权限?
func (this *ShareService) HasUpdatePerm(userId, updatedUserId, noteId string) bool {
	q := this.getOrQ(updatedUserId) // (toUserId == "xxx" || ToGroupId in (1, 2,3))
	q["UserId"] = bson.ObjectIdHex(userId)
	q["NoteId"] = bson.ObjectIdHex(noteId)

	// note的权限
	shares := []info.ShareNote{}
	db.ShareNotes.Find(q).Sort("-ToUserId").All(&shares) // 个人 > 组织
	for _, share := range shares {
		return share.Perm == 1 // 第1个权限最大
	}

	// notebook的权限
	notebookId := noteService.GetNotebookId(noteId)
	if notebookId.Hex() == "" {
		return false
	}

	delete(q, "NoteId")
	q["NotebookId"] = notebookId
	shares2 := []info.ShareNotebook{}
	db.ShareNotebooks.Find(q).Sort("-ToUserId").All(&shares2) // 个人 > 组织
	for _, share := range shares2 {
		return share.Perm == 1 // 第1个权限最大
	}
	return false
}
开发者ID:sunyinhuiCoding,项目名称:leanote,代码行数:28,代码来源:ShareService.go

示例6: UpdateTask

func (c *ApiConnection) UpdateTask(w http.ResponseWriter, r *http.Request) {
	token := r.FormValue("token")
	todoID := r.FormValue("todo_id")
	todoTitle := r.FormValue("todo_title")
	todoBody := r.FormValue("todo_body")

	todoCompleted, _ := strconv.ParseBool(r.FormValue("complete"))
	todoDueDate := r.FormValue("due_date")

	timeFormatted, _ := time.Parse(time.RFC3339, todoDueDate)

	todo := &Todo{
		Id:        bson.ObjectIdHex(todoID),
		UserID:    bson.ObjectIdHex(token),
		Title:     todoTitle,
		Body:      todoBody,
		Completed: todoCompleted,
		Due:       timeFormatted}

	err := c.dbConnection.UpdateExistingTask(todo)

	if !err {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusNotFound)
		if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Error updating task"}); err != nil {
			panic(err)
		}
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
}
开发者ID:zarkopopovski,项目名称:godo,代码行数:32,代码来源:handlers.go

示例7: GetBook

func GetBook(n string) *Book {
	b := new(Book)
	switch n {
	case "MobyDick":
		b.Id = bson.ObjectIdHex("51e9ad9749a1b71843000001")
		b.Title = "Moby Dick"
		b.Body = "Queequeg was a native of Rokovoko, an island far away to the West and South. It is not down in any map; true places never are.\n\nWhen a new-hatched savage running wild about his native woodlands in a grass clout, followed by the nibbling goats, as if he were a green sapling; even then, in Queequeg's ambitious soul, lurked a strong desire to see something more of Christendom than a specimen whaler or two. His father was a High Chief, a King; his uncle a High Priest; and on the maternal side he boasted aunts who were the wives of unconquerable warriors. There was excellent blood in his veins—royal stuff; though sadly vitiated, I fear, by the cannibal propensity he nourished in his untutored youth.\n\nA Sag Harbor ship visited his father's bay, and Queequeg sought a passage to Christian lands. But the ship, having her full complement of seamen, spurned his suit; and not all the King his father's influence could prevail. But Queequeg vowed a vow. Alone in his canoe, he paddled off to a distant strait, which he knew the ship must pass through when she quitted the island. On one side was a coral reef; on the other a low tongue of land, covered with mangrove thickets that grew out into the water. Hiding his canoe, still afloat, among these thickets, with its prow seaward, he sat down in the stern, paddle low in hand; and when the ship was gliding by, like a flash he darted out; gained her side; with one backward dash of his foot capsized and sank his canoe; climbed up the chains; and throwing himself at full length upon the deck, grappled a ring-bolt there, and swore not to let it go, though hacked in pieces.\n\nIn vain the captain threatened to throw him overboard; suspended a cutlass over his naked wrists; Queequeg was the son of a King, and Queequeg budged not. Struck by his desperate dauntlessness, and his wild desire to visit Christendom, the captain at last relented, and told him he might make himself at home. But this fine young savage—this sea Prince of Wales, never saw the Captain's cabin. They put him down among the sailors, and made a whaleman of him. But like Czar Peter content to toil in the shipyards of foreign cities, Queequeg disdained no seeming ignominy, if thereby he might happily gain the power of enlightening his untutored countrymen. For at bottom—so he told me—he was actuated by a profound desire to learn among the Christians, the arts whereby to make his people still happier than they were; and more than that, still better than they were. But, alas! the practices of whalemen soon convinced him that even Christians could be both miserable and wicked; infinitely more so, than all his father's heathens. Arrived at last in old Sag Harbor; and seeing what the sailors did there; and then going on to Nantucket, and seeing how they spent their wages in that place also, poor Queequeg gave it up for lost. Thought he, it's a wicked world in all meridians; I'll die a pagan.\n\nAnd thus an old idolator at heart, he yet lived among these Christians, wore their clothes, and tried to talk their gibberish. Hence the queer ways about him, though now some time from home."
		b.Tags = []string{"Herman Melville", "Classics"}
	case "AroundWorld":
		b.Id = bson.ObjectIdHex("51e9ad9749a1b71843000002")
		b.Title = "Around the World in 80 Days"
		b.Body = "\"The owners are myself,\" replied the captain.  \"The vessel belongs to me.\"\n\n\"I will freight it for you.\"\n\n\"No.\"\n\n\"I will buy it of you.\"\n\n\"No.\"\n\nPhileas Fogg did not betray the least disappointment; but the situation was a grave one.  It was not at New York as at Hong Kong, nor with the captain of the Henrietta as with the captain of the Tankadere.  Up to this time money had smoothed away every obstacle.  Now money failed.\n\nStill, some means must be found to cross the Atlantic on a boat, unless by balloon—which would have been venturesome, besides not being capable of being put in practice.  It seemed that Phileas Fogg had an idea, for he said to the captain, \"Well, will you carry me to Bordeaux?\"\n\n\"No, not if you paid me two hundred dollars.\""
		b.Tags = []string{"Jules Verne", "Classics", "Contemporary", "Action", "Adventure", "Suspense", "Fantasy"}
	case "PrincessMars":
		b.Id = bson.ObjectIdHex("51e9ae1749a1b71843000004")
		b.Title = "A Princess of Mars"
		b.Body = "Tal Hajus arose, and I, half fearing, half anticipating his intentions, hurried to the winding runway which led to the floors below.  No one was near to intercept me, and I reached the main floor of the chamber unobserved, taking my station in the shadow of the same column that Tars Tarkas had but just deserted.  As I reached the floor Tal Hajus was speaking.\n\n\"Princess of Helium, I might wring a mighty ransom from your people would I but return you to them unharmed, but a thousand times rather would I watch that beautiful face writhe in the agony of torture; it shall be long drawn out, that I promise you; ten days of pleasure were all too short to show the love I harbor for your race.  The terrors of your death shall haunt the slumbers of the red men through all the ages to come; they will shudder in the shadows of the night as their fathers tell them of the awful vengeance of the green men; of the power and might and hate and cruelty of Tal Hajus.  But before the torture you shall be mine for one short hour, and word of that too shall go forth to Tardos Mors, Jeddak of Helium, your grandfather, that he may grovel upon the ground in the agony of his sorrow.  Tomorrow the torture will commence; tonight thou art Tal Hajus'; come!\"\n\nHe sprang down from the platform and grasped her roughly by the arm, but scarcely had he touched her than I leaped between them.  My short-sword, sharp and gleaming was in my right hand; I could have plunged it into his putrid heart before he realized that I was upon him; but as I raised my arm to strike I thought of Tars Tarkas, and, with all my rage, with all my hatred, I could not rob him of that sweet moment for which he had lived and hoped all these long, weary years, and so, instead, I swung my good right fist full upon the point of his jaw.  Without a sound he slipped to the floor as one dead.\n\nIn the same deathly silence I grasped Dejah Thoris by the hand, and motioning Sola to follow we sped noiselessly from the chamber and to the floor above.  Unseen we reached a rear window and with the straps and leather of my trappings I lowered, first Sola and then Dejah Thoris to the ground below.  Dropping lightly after them I drew them rapidly around the court in the shadows of the buildings, and thus we returned over the same course I had so recently followed from the distant boundary of the city.\n\nWe finally came upon my thoats in the courtyard where I had left them, and placing the trappings upon them we hastened through the building to the avenue beyond.  Mounting, Sola upon one beast, and Dejah Thoris behind me upon the other, we rode from the city of Thark through the hills to the south.\n\nInstead of circling back around the city to the northwest and toward the nearest waterway which lay so short a distance from us, we turned to the northeast and struck out upon the mossy waste across which, for two hundred dangerous and weary miles, lay another main artery leading to Helium."
		b.Tags = []string{"Edgar Rice Burroughs", "Adventure"}
	case "EarthsCore":
		b.Id = bson.ObjectIdHex("51e9ae4949a1b71843000005")
		b.Title = "At the Earth's Core"
		b.Body = "With no heavenly guide, it is little wonder that I became confused and lost in the labyrinthine maze of those mighty hills.  What, in reality, I did was to pass entirely through them and come out above the valley upon the farther side.  I know that I wandered for a long time, until tired and hungry I came upon a small cave in the face of the limestone formation which had taken the place of the granite farther back.\n\nThe cave which took my fancy lay halfway up the precipitous side of a lofty cliff.  The way to it was such that I knew no extremely formidable beast could frequent it, nor was it large enough to make a comfortable habitat for any but the smaller mammals or reptiles.  Yet it was with the utmost caution that I crawled within its dark interior.\n\nHere I found a rather large chamber, lighted by a narrow cleft in the rock above which let the sunlight filter in in sufficient quantities partially to dispel the utter darkness which I had expected.  The cave was entirely empty, nor were there any signs of its having been recently occupied.  The opening was comparatively small, so that after considerable effort I was able to lug up a bowlder from the valley below which entirely blocked it.\n\nThen I returned again to the valley for an armful of grasses and on this trip was fortunate enough to knock over an orthopi, the diminutive horse of Pellucidar, a little animal about the size of a fox terrier, which abounds in all parts of the inner world.  Thus, with food and bedding I returned to my lair, where after a meal of raw meat, to which I had now become quite accustomed, I dragged the bowlder before the entrance and curled myself upon a bed of grasses—a naked, primeval, cave man, as savagely primitive as my prehistoric progenitors.\n\nI awoke rested but hungry, and pushing the bowlder aside crawled out upon the little rocky shelf which was my front porch.  Before me spread a small but beautiful valley, through the center of which a clear and sparkling river wound its way down to an inland sea, the blue waters of which were just visible between the two mountain ranges which embraced this little paradise.  The sides of the opposite hills were green with verdure, for a great forest clothed them to the foot of the red and yellow and copper green of the towering crags which formed their summit.  The valley itself was carpeted with a luxuriant grass, while here and there patches of wild flowers made great splashes of vivid color against the prevailing green."
		b.Tags = []string{"Edgar Rice Burroughs", "Adventure", "Action", "Fantasy", "Science Fiction"}
	case "WarWorlds":
		b.Id = bson.ObjectIdHex("51e9af2749a1b71843000006")
		b.Title = "The War of the Worlds Book I"
		b.Body = "\"Did you see a man in the pit?\" I said; but he made no answer to that.  We became silent, and stood watching for a time side by side, deriving, I fancy, a certain comfort in one another's company.  Then I shifted my position to a little knoll that gave me the advantage of a yard or more of elevation and when I looked for him presently he was walking towards Woking.\n\nThe sunset faded to twilight before anything further happened.  The crowd far away on the left, towards Woking, seemed to grow, and I heard now a faint murmur from it.  The little knot of people towards Chobham dispersed.  There was scarcely an intimation of movement from the pit.\n\nIt was this, as much as anything, that gave people courage, and I suppose the new arrivals from Woking also helped to restore confidence.  At any rate, as the dusk came on a slow, intermittent movement upon the sand pits began, a movement that seemed to gather force as the stillness of the evening about the cylinder remained unbroken.  Vertical black figures in twos and threes would advance, stop, watch, and advance again, spreading out as they did so in a thin irregular crescent that promised to enclose the pit in its attenuated horns.  I, too, on my side began to move towards the pit.\n\nThen I saw some cabmen and others had walked boldly into the sand pits, and heard the clatter of hoofs and the gride of wheels.  I saw a lad trundling off the barrow of apples.  And then, within thirty yards of the pit, advancing from the direction of Horsell, I noted a little black knot of men, the foremost of whom was waving a white flag.\n\nThis was the Deputation.  There had been a hasty consultation, and since the Martians were evidently, in spite of their repulsive forms, intelligent creatures, it had been resolved to show them, by approaching them with signals, that we too were intelligent."
		b.Tags = []string{"H. G. Wells", "Science Fiction", "Classics"}
	}
	return b
}
开发者ID:oblank,项目名称:revel-mgo,代码行数:31,代码来源:book.go

示例8: CommentPostController

// CommentPostController will answer a JSON of the post
func CommentPostController(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Println(err)
	}
	var comment Comment
	if err := json.Unmarshal([]byte(string(body)), &comment); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(bson.M{"error": "Mauvais Format"})
		return
	}

	isValid := VerifyUserRequest(r, comment.User)
	if !isValid {
		w.WriteHeader(http.StatusUnauthorized)
		json.NewEncoder(w).Encode(bson.M{"error": "Contenu Protégé"})
		return
	}

	comment.ID = bson.NewObjectId()
	comment.Date = time.Now()

	vars := mux.Vars(r)
	postID := vars["id"]
	res := CommentPost(bson.ObjectIdHex(postID), comment)
	json.NewEncoder(w).Encode(res)

	for _, tag := range comment.Tags {
		go TriggerNotificationForUser(comment.User, bson.ObjectIdHex(tag.User), res.ID, "@"+GetUser(comment.User).Username+" t'a taggé sur \""+res.Title+"\"", comment)
	}
}
开发者ID:fthomasmorel,项目名称:insapp-go,代码行数:32,代码来源:postController.go

示例9: TestObjectIds

func TestObjectIds(t *testing.T) {
	in := map[string]interface{}{
		"nil": nil,
		"id1": "ffffffffffffffffffffffff",
		"nested": map[string]interface{}{
			"id2": "111111111111111111111111",
			"int": 5,
			"str": "test",
		},
	}

	expected := map[string]interface{}{
		"nil": nil,
		"id1": bson.ObjectIdHex("ffffffffffffffffffffffff"),
		"nested": map[string]interface{}{
			"id2": bson.ObjectIdHex("111111111111111111111111"),
			"int": 5,
			"str": "test",
		},
	}

	setObjectIds(in)

	assert.Equal(t, expected, in)
}
开发者ID:bgveenstra,项目名称:moredis,代码行数:25,代码来源:templating_test.go

示例10: NoteByID

// NoteByID gets note by ID
func NoteByID(userID string, noteID string) (Note, error) {
	var err error

	result := Note{}

	if database.CheckConnection() {
		// Create a copy of mongo
		session := database.Mongo.Copy()
		defer session.Close()
		c := session.DB(database.ReadConfig().MongoDB.Database).C("note")

		// Validate the object id
		if bson.IsObjectIdHex(noteID) {
			err = c.FindId(bson.ObjectIdHex(noteID)).One(&result)
			if result.UserID != bson.ObjectIdHex(userID) {
				result = Note{}
				err = ErrUnauthorized
			}
		} else {
			err = ErrNoResult
		}
	} else {
		err = ErrUnavailable
	}

	return result, standardizeError(err)
}
开发者ID:atabek,项目名称:gowebapp,代码行数:28,代码来源:note.go

示例11: PreNextBlog

// 上一篇文章, 下一篇文章
// sorterField, baseTime是基准, sorterField=PublicTime, title
// isAsc是用户自定义的排序方式
func (this *BlogService) PreNextBlog(userId string, sorterField string, isAsc bool, noteId string, baseTime interface{}) (info.Post, info.Post) {
	userIdO := bson.ObjectIdHex(userId)

	var sortFieldT1, sortFieldT2 bson.M
	var sortFieldR1, sortFieldR2 string
	if !isAsc {
		// 降序
		/*
			------- pre
			----- now
			--- next
			--
		*/
		// 上一篇时间要比它大, 找最小的
		sortFieldT1 = bson.M{"$gte": baseTime} // 为什么要相等, 因为将notebook发布成博客, 会统一修改note的publicTime, 此时所有notes都一样
		sortFieldR1 = sorterField
		// 下一篇时间要比它小
		sortFieldT2 = bson.M{"$lte": baseTime}
		sortFieldR2 = "-" + sorterField
	} else {
		// 升序
		/*
		   --- pre
		   ----- now
		   ------- next
		   ---------
		*/
		// 上一篇要比它小, 找最大的
		sortFieldT1 = bson.M{"$lte": baseTime}
		sortFieldR1 = "-" + sorterField
		// 下一篇, 找最小的
		sortFieldT2 = bson.M{"$gte": baseTime}
		sortFieldR2 = sorterField
	}

	// 上一篇, 比基时间要小, 但是是最后一篇, 所以是降序
	note := info.Note{}
	query := bson.M{"UserId": userIdO,
		"IsTrash":   false,
		"IsBlog":    true,
		"_id":       bson.M{"$ne": bson.ObjectIdHex(noteId)},
		sorterField: sortFieldT1,
	}
	q := db.Notes.Find(query)
	q.Sort(sortFieldR1).Limit(1).One(&note)

	// 下一篇, 比基时间要大, 但是是第一篇, 所以是升序
	if note.NoteId != "" {
		query["_id"] = bson.M{"$nin": []bson.ObjectId{bson.ObjectIdHex(noteId), note.NoteId}}
	}
	note2 := info.Note{}
	query[sorterField] = sortFieldT2
	//	Log(isAsc)
	//	LogJ(query)
	//	Log(sortFieldR2)
	q = db.Notes.Find(query)
	q.Sort(sortFieldR2).Limit(1).One(&note2)

	return this.FixNote(note), this.FixNote(note2)
}
开发者ID:sunyinhuiCoding,项目名称:leanote,代码行数:63,代码来源:BlogService.go

示例12: adminEditPackageCategoryHandler

// URL: /admin/package_category/{id}/edit
// 修改包分类
func adminEditPackageCategoryHandler(handler *Handler) {
	id := mux.Vars(handler.Request)["id"]
	c := handler.DB.C(PACKAGE_CATEGORIES)
	var category PackageCategory
	c.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&category)

	form := wtforms.NewForm(
		wtforms.NewTextField("id", "ID", category.Id, wtforms.Required{}),
		wtforms.NewTextField("name", "名称", category.Name, wtforms.Required{}),
	)

	if handler.Request.Method == "POST" {
		if !form.Validate(handler.Request) {
			handler.renderTemplate("package_category/form.html", ADMIN, map[string]interface{}{"form": form})
			return
		}

		c.Update(bson.M{"_id": bson.ObjectIdHex(id)}, bson.M{"$set": bson.M{
			"id":   form.Value("id"),
			"name": form.Value("name"),
		}})

		http.Redirect(handler.ResponseWriter, handler.Request, "/admin/package_categories", http.StatusFound)
	}

	handler.renderTemplate("package_category/form.html", ADMIN, map[string]interface{}{
		"form":  form,
		"isNew": false,
	})
}
开发者ID:ZuiGuangYin,项目名称:gopher,代码行数:32,代码来源:package_category.go

示例13: CopySharedNote

// 复制别人的共享笔记给我
// TODO 判断是否共享了给我
func (this *NoteService) CopySharedNote(noteId, notebookId, fromUserId, myUserId string) info.Note {
	if notebookService.IsMyNotebook(notebookId, myUserId) {
		note := this.GetNote(noteId, fromUserId)
		if note.NoteId == "" {
			return info.Note{}
		}
		noteContent := this.GetNoteContent(noteId, fromUserId)

		// 重新生成noteId
		note.NoteId = bson.NewObjectId()
		note.NotebookId = bson.ObjectIdHex(notebookId)
		note.UserId = bson.ObjectIdHex(myUserId)
		note.IsTop = false
		note.IsBlog = false // 别人的可能是blog

		// content
		noteContent.NoteId = note.NoteId
		noteContent.UserId = note.UserId

		// 添加之
		note = this.AddNoteAndContent(note, noteContent, note.UserId)

		// 更新blog状态
		isBlog := this.updateToNotebookBlog(note.NoteId.Hex(), notebookId, myUserId)

		note.IsBlog = isBlog
		return note
	}

	return info.Note{}
}
开发者ID:bigxing,项目名称:leanote,代码行数:33,代码来源:NoteService.go

示例14: databaseUpdate

func databaseUpdate(PutParams PutParameters, id string) (ResParameters, error) {
	/*	uri := os.Getenv("MONGOHQ_URL")
		if uri == "" {
			fmt.Println("no connection string provided")
			os.Exit(1)
		}*/
	//URL := "mongodb://ashwini:[email protected]:45064/cmpe273"
	sess, err := mgo.Dial(Url)
	if err != nil {
		fmt.Printf("Can't connect to mongo, go error %v\n", err)
		os.Exit(1)
	}
	defer sess.Close()
	sess.SetSafe(&mgo.Safe{})
	collection := sess.DB("cmpe273").C("AddressBook")

	//doc := PutParams

	change := bson.M{"$set": bson.M{"address": PutParams.Address, "city": PutParams.City, "state": PutParams.State, "zip": PutParams.Zip, "coord": PutParams.Coord}}
	err = collection.Update(bson.M{"_id": bson.ObjectIdHex(id)}, change)
	data := ResParameters{}
	err = collection.Find(bson.M{"_id": bson.ObjectIdHex(id)}).Select(bson.M{}).One(&data)

	return data, err
}
开发者ID:ashwinibalaraman,项目名称:cmpe-273-assignment2,代码行数:25,代码来源:assignment2.go

示例15: DelAdmin

// DelAdmin removes a member from an existing group
func DelAdmin(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Get group id and convert from string to objectId
	rawMID := c.Param("mid")
	if !bson.IsObjectIdHex(rawMID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	memberID := bson.ObjectIdHex(rawMID)

	// Get group id and convert from string to objectId
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	groupID := bson.ObjectIdHex(rawGID)
	err := mangos.Update(constants.CGroups, bson.M{
		"$and": []bson.M{
			bson.M{"_id": groupID},
			bson.M{"admins": digitsID},
		},
	}, bson.M{"$pull": bson.M{"admins": memberID}})
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok("deleted admin")
}
开发者ID:cedmundo,项目名称:hablo,代码行数:36,代码来源:groups.go


注:本文中的gopkg/in/mgo/v2/bson.ObjectIdHex函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。