Golang ObjectIdHex示例

说明

golang objectidhex示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: gopkg/in/mgo/v2/bson

示例#1
文件: TagService.go 项目: nosqldb/zhujian

// 添加或更新标签, 先查下是否存在, 不存在则添加, 存在则更新
// 都要统计下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}, ¬eTag)

	// 存在, 则更新之
	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
}

示例#2
文件: ShareService.go 项目: sunyinhuiCoding/leanote

// 得到笔记本分享给的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
}

示例#3
文件: prova.go 项目: GrupoEstudoMega/MegaRunning

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

示例#4
文件: BlogService.go 项目: ZypcGroup/leanote

// 点赞
// 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
}

示例#5
文件: ShareService.go 项目: sunyinhuiCoding/leanote

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

示例#6
文件: handlers.go 项目: zarkopopovski/godo

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

示例#7
文件: book.go 项目: oblank/revel-mgo

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
}

示例#8
文件: postController.go 项目: fthomasmorel/insapp-go

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

示例#9
文件: templating_test.go 项目: bgveenstra/moredis

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

示例#10
文件: note.go 项目: atabek/gowebapp

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

示例#11
文件: BlogService.go 项目: sunyinhuiCoding/leanote

// 上一篇文章, 下一篇文章
// 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(¬e)

	// 下一篇, 比基时间要大, 但是是第一篇, 所以是升序
	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(¬e2)

	return this.FixNote(note), this.FixNote(note2)
}

示例#12
文件: package_category.go 项目: ZuiGuangYin/gopher

// 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,
	})
}

示例#13
文件: NoteService.go 项目: bigxing/leanote

// 复制别人的共享笔记给我
// 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{}
}

示例#14
文件: assignment2.go 项目: ashwinibalaraman/cmpe-273-assignment2

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
}

示例#15
文件: groups.go 项目: cedmundo/hablo

// 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")
}

示例#16
文件: product.go 项目: zarkopopovski/goinvoicing

func (product *Product) FindProductsByIDs(mConnection *MongoConnection, token string, productsIDs []string) []Product {
	if mConnection.dbSession == nil {
		return nil
	}

	session := mConnection.dbSession.Copy()
	defer session.Close()

	objectsArray := make([]bson.ObjectId, len(productsIDs))

	for i := 0; i < len(productsIDs); i++ {
		objectsArray[i] = bson.ObjectIdHex(productsIDs[i])
	}

	var products Products

	c := session.DB("goinvoice").C("productdata")
	err := c.Find(
		bson.M{"user_id": bson.ObjectIdHex(token),
			"$and": []interface{}{
				bson.M{"_id": []interface{}{
					bson.M{"$in": objectsArray}}}}}).All(&products)
	if err != nil {
		log.Fatal(err)
	}

	return products
}

示例#17
文件: db.go 项目: hheld/UserAdminWebApp

func updateUserPwdInDb(userId, newPwd, currentPwd string) error {
	if dbCollection == nil {
		return errors.New("There is no connection to a database!")
	}

	result := User{}
	err := dbCollection.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(&result)

	if err != nil {
		return err
	}

	_, err = validateUserInDb(result.UserName, currentPwd)

	if err != nil {
		return err
	}

	hashedPwd, err := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)

	if err != nil {
		return err
	}

	return dbCollection.Update(bson.M{"_id": bson.ObjectIdHex(userId)}, bson.M{"$set": bson.M{
		"passwordhash": hashedPwd,
	}})
}

示例#18
文件: NoteService.go 项目: JacobXie/leanote-daocloud

// 列出note, 排序规则, 还有分页
// CreatedTime, UpdatedTime, title 来排序
func (this *NoteService) ListNotes(userId, notebookId string,
	isTrash bool, pageNumber, pageSize int, sortField string, isAsc bool, isBlog bool) (count int, notes []info.Note) {
	notes = []info.Note{}
	skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, sortField, isAsc)

	// 不是trash的
	query := bson.M{"UserId": bson.ObjectIdHex(userId), "IsTrash": isTrash, "IsDeleted": false}
	if isBlog {
		query["IsBlog"] = true
	}
	if notebookId != "" {
		query["NotebookId"] = bson.ObjectIdHex(notebookId)
	}

	q := db.Notes.Find(query)

	// 总记录数
	count, _ = q.Count()

	q.Sort(sortFieldR).
		Skip(skipNum).
		Limit(pageSize).
		All(¬es)
	return
}

示例#19
文件: ThemeService.go 项目: nosqldb/zhujian

// 更新模板内容
func (this *ThemeService) UpdateTplContent(userId, themeId, filename, content string) (ok bool, msg string) {
	basePath := this.GetThemeAbsolutePath(userId, themeId)
	path := basePath + "/" + filename
	if strings.Contains(filename, ".html") {
		Log(">>")
		if ok, msg = this.ValidateTheme(basePath, filename, content); ok {
			// 模板
			if ok, msg = this.mustTpl(filename, content); ok {
				ok = PutFileStrContent(path, content)
			}
		}
		return
	} else if filename == "theme.json" {
		// 主题配置, 判断是否是正确的json
		theme, err := this.parseConfig(content)
		if err != nil {
			return false, fmt.Sprintf("%v", err)
		}
		// 正确, 更新theme信息
		ok = db.UpdateByQMap(db.Themes, bson.M{"_id": bson.ObjectIdHex(themeId), "UserId": bson.ObjectIdHex(userId)},
			bson.M{
				"Name":      theme.Name,
				"Version":   theme.Version,
				"Author":    theme.Author,
				"AuthorUrl": theme.AuthorUrl,
				"Info":      theme.Info,
			})
		if ok {
			ok = PutFileStrContent(path, content)
		}
		return
	}
	ok = PutFileStrContent(path, content)
	return
}

示例#20
文件: AttachService.go 项目: sunyinhuiCoding/leanote

// 复制笔记时需要复制附件
// noteService调用, 权限已判断
func (this *AttachService) CopyAttachs(noteId, toNoteId, toUserId string) bool {
	attachs := []info.Attach{}
	db.ListByQ(db.Attachs, bson.M{"NoteId": bson.ObjectIdHex(noteId)}, &attachs)

	// 复制之
	toNoteIdO := bson.ObjectIdHex(toNoteId)
	for _, attach := range attachs {
		attach.AttachId = ""
		attach.NoteId = toNoteIdO

		// 文件复制一份
		_, ext := SplitFilename(attach.Name)
		newFilename := NewGuid() + ext
		dir := "files/" + toUserId + "/attachs"
		filePath := dir + "/" + newFilename
		err := os.MkdirAll(revel.BasePath+"/"+dir, 0755)
		if err != nil {
			return false
		}
		_, err = CopyFile(revel.BasePath+"/"+attach.Path, revel.BasePath+"/"+filePath)
		if err != nil {
			return false
		}
		attach.Name = newFilename
		attach.Path = filePath

		this.AddAttach(attach)
	}

	return true
}

示例#21
文件: FileService.go 项目: sunyinhuiCoding/leanote

// list images
// if albumId == "" get default album images
func (this *FileService) ListImagesWithPage(userId, albumId, key string, pageNumber, pageSize int) info.Page {
	skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, "CreatedTime", false)
	files := []info.File{}

	q := bson.M{"UserId": bson.ObjectIdHex(userId), "Type": ""} // life
	if albumId != "" {
		q["AlbumId"] = bson.ObjectIdHex(albumId)
	} else {
		q["IsDefaultAlbum"] = true
	}
	if key != "" {
		q["Title"] = bson.M{"$regex": bson.RegEx{".*?" + key + ".*", "i"}}
	}

	//	LogJ(q)

	count := db.Count(db.Files, q)

	db.Files.
		Find(q).
		Sort(sortFieldR).
		Skip(skipNum).
		Limit(pageSize).
		All(&files)

	return info.Page{Count: count, List: files}
}

示例#22
文件: FileService.go 项目: ClaudeXin/leanote

// 是否是我的文件
func (this *FileService) IsMyFile(userId, fileId string) bool {
	// 如果有问题会panic
	if !bson.IsObjectIdHex(fileId) || !bson.IsObjectIdHex(userId) {
		return false
	}
	return db.Has(db.Files, bson.M{"UserId": bson.ObjectIdHex(userId), "_id": bson.ObjectIdHex(fileId)})
}

示例#23
文件: BlogService.go 项目: ZypcGroup/leanote

// 点赞/取消赞
func (this *BlogService) LikeComment(commentId, userId string) (ok bool, isILike bool, num int) {
	ok = false
	isILike = false
	num = 0
	comment := info.BlogComment{}

	db.Get(db.BlogComments, commentId, &comment)

	var n int
	if comment.LikeUserIds != nil && len(comment.LikeUserIds) > 0 && InArray(comment.LikeUserIds, userId) {
		n = -1
		// 从点赞名单删除
		db.Update(db.BlogComments, bson.M{"_id": bson.ObjectIdHex(commentId)},
			bson.M{"$pull": bson.M{"LikeUserIds": userId}})
		isILike = false
	} else {
		n = 1
		// 添加之
		db.Update(db.BlogComments, bson.M{"_id": bson.ObjectIdHex(commentId)},
			bson.M{"$push": bson.M{"LikeUserIds": userId}})
		isILike = true
	}

	if comment.LikeUserIds == nil {
		num = 0
	} else {
		num = len(comment.LikeUserIds) + n
	}

	ok = db.Update(db.BlogComments, bson.M{"_id": bson.ObjectIdHex(commentId)},
		bson.M{"$set": bson.M{"LikeNum": num}})

	return
}

示例#24
文件: returnsession.go 项目: Jmeyering/aa-stats

// returnSession returns an existing gameSession response to the response.
func returnGameSession(c web.C, w http.ResponseWriter, r *http.Request) {

	// Find the gameSession by the id parameter in the url
	gameSession, err := GetGameSessionBy("_id", bson.ObjectIdHex(c.URLParams["id"]))

	// GameSession could not be found
	if err != nil {
		io.WriteString(w, c.URLParams["id"]+" "+err.Error())
		w.WriteHeader(404)
		return
	}

	// Then we want to actually find the game
	game, err := GetGameBy("_id", bson.ObjectIdHex(gameSession.GameId))

	// Game could not be found
	if err != nil {
		io.WriteString(w, "game "+gameSession.GameId+" not found")
		w.WriteHeader(404)
		return
	}

	gameSessionResource := hal.NewResource(gameSession, "/sessions/"+gameSession.ID.Hex())
	gameResource := hal.NewResource(game, "/games/"+gameSession.GameId)

	gameSessionResource.Embed("game", gameResource)
	gameSessionResource.AddNewLink("game", "/games/"+gameSession.GameId)

	j, _ := json.Marshal(gameSessionResource)

	io.WriteString(w, string(j))
}

示例#25
文件: ShareService.go 项目: sunyinhuiCoding/leanote

func (this *ShareService) UpdateShareNotebookPerm(notebookId string, perm int, userId, toUserId string) bool {
	return db.UpdateByQField(db.ShareNotebooks,
		bson.M{"NotebookId": bson.ObjectIdHex(notebookId), "UserId": bson.ObjectIdHex(userId), "ToUserId": bson.ObjectIdHex(toUserId)},
		"Perm",
		perm,
	)
}

示例#26
文件: handlers.go 项目: zarkopopovski/goinvoicing

func (c *ApiConnection) UpdateProduct(w http.ResponseWriter, r *http.Request) {
	token := r.FormValue("token")
	productID := r.FormValue("product_id")
	name := r.FormValue("name")
	description := r.FormValue("description")
	price := r.FormValue("price")
	tax := r.FormValue("tax")

	validProduct, _ := strconv.ParseBool(r.FormValue("valid"))

	product := &Product{
		Id:          bson.ObjectIdHex(productID),
		UserID:      bson.ObjectIdHex(token),
		Name:        name,
		Description: description,
		Price:       price,
		Tax:         tax,
		Valid:       validProduct}

	result := c.dbConnection.UpdateProduct(product)

	if result {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		return
	}

	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 product"}); err != nil {
		panic(err)
	}
}

示例#27
文件: NotebookService.go 项目: sunyinhuiCoding/leanote

// ToBlog or Not
func (this *NotebookService) ToBlog(userId, notebookId string, isBlog bool) bool {
	// 笔记本
	db.UpdateByIdAndUserIdMap(db.Notebooks, notebookId, userId, bson.M{"IsBlog": isBlog})

	// 更新笔记
	q := bson.M{"UserId": bson.ObjectIdHex(userId),
		"NotebookId": bson.ObjectIdHex(notebookId)}
	data := bson.M{"IsBlog": isBlog}
	if isBlog {
		data["PublicTime"] = time.Now()
	} else {
		data["HasSelfDefined"] = false
	}
	db.UpdateByQMap(db.Notes, q, data)

	// noteContents也更新, 这个就麻烦了, noteContents表没有NotebookId
	// 先查该notebook下所有notes, 得到id
	notes := []info.Note{}
	db.ListByQWithFields(db.Notes, q, []string{"_id"}, ¬es)
	if len(notes) > 0 {
		noteIds := make([]bson.ObjectId, len(notes))
		for i, each := range notes {
			noteIds[i] = each.NoteId
		}
		db.UpdateByQMap(db.NoteContents, bson.M{"_id": bson.M{"$in": noteIds}}, bson.M{"IsBlog": isBlog})
	}

	// 重新计算tags
	go (func() {
		blogService.ReCountBlogTags(userId)
	})()

	return true
}

示例#28
文件: objectid_test.go 项目: devsaurin/mongo-tools

func TestObjectIdValue(t *testing.T) {

	Convey("When converting JSON with ObjectId values", t, func() {

		Convey("works for ObjectId constructor", func() {
			key := "key"
			jsonMap := map[string]interface{}{
				key: json.ObjectId("0123456789abcdef01234567"),
			}

			err := ConvertJSONDocumentToBSON(jsonMap)
			So(err, ShouldBeNil)
			So(jsonMap[key], ShouldEqual, bson.ObjectIdHex("0123456789abcdef01234567"))
		})

		Convey(`works for ObjectId document ('{ "$oid": "0123456789abcdef01234567" }')`, func() {
			key := "key"
			jsonMap := map[string]interface{}{
				key: map[string]interface{}{
					"$oid": "0123456789abcdef01234567",
				},
			}

			err := ConvertJSONDocumentToBSON(jsonMap)
			So(err, ShouldBeNil)
			So(jsonMap[key], ShouldEqual, bson.ObjectIdHex("0123456789abcdef01234567"))
		})
	})
}

示例#29
文件: GroupService.go 项目: nosqldb/zhujian

// 判断组中是否包含指定用户
func (this *GroupService) IsExistsGroupUser(userId, groupId string) (ok bool) {
	// 如果我拥有这个组, 那也行
	if this.isMyGroup(userId, groupId) {
		return true
	}
	return db.Has(db.GroupUsers, bson.M{"UserId": bson.ObjectIdHex(userId), "GroupId": bson.ObjectIdHex(groupId)})
}

示例#30
文件: hostservice.go 项目: popsuper1982/DCOS_Cluster

func (p *HostService) UpdateById(objectId string, host entity.Host, x_auth_token string) (created bool,
	errorCode string, err error) {
	logrus.Infof("start to update host [%v]", host)
	// do authorize first
	if authorized := GetAuthService().Authorize("update_host", x_auth_token, objectId, p.collectionName); !authorized {
		err = errors.New("required opertion is not authorized!")
		errorCode = COMMON_ERROR_UNAUTHORIZED
		logrus.Errorf("update host with objectId [%v] error is %v", objectId, err)
		return
	}

	if !bson.IsObjectIdHex(objectId) {
		err = errors.New("invalide ObjectId.")
		errorCode = COMMON_ERROR_INVALIDATE
		return
	}

	// FIXING
	//	hostquery, _, _  := p.QueryById(objectId, x_auth_token)
	var selector = bson.M{}
	selector["_id"] = bson.ObjectIdHex(objectId)

	host.ObjectId = bson.ObjectIdHex(objectId)
	host.TimeUpdate = dao.GetCurrentTime()

	logrus.Infof("start to change host")
	err = dao.HandleUpdateByQueryPartial(p.collectionName, selector, &host)
	//	created, err = dao.HandleUpdateOne(&host, dao.QueryStruct{p.collectionName, selector, 0, 0, ""})
	if err != nil {
		logrus.Errorf("update host [%v] error is %v", host, err)
		errorCode = HOST_ERROR_UPDATE
	}
	created = true
	return
}

展开阅读全文