本文整理汇总了Golang中labix/org/v2/mgo/bson.NewObjectId函数的典型用法代码示例。如果您正苦于以下问题:Golang NewObjectId函数的具体用法?Golang NewObjectId怎么用?Golang NewObjectId使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewObjectId函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: SetUpSuite
func (s MySuite) SetUpSuite(c *gocheck.C) {
d, err := Connect("")
if err != nil {
c.Fatalf("Unable to connect to database!")
}
db = d
// create a test user
u := User{ID: bson.NewObjectId(), Email: "[email protected]", Phone: "5555555555"}
err = db.Users.Insert(u)
if err != nil {
c.Fatalf("Can't insert document: %v\n", err)
}
// create a test notification
n := Notification{ID: bson.NewObjectId(),
Type: "text",
Team: "7332",
User: "[email protected]",
Advance: true,
Award: true,
Alliance: true,
}
err = db.Notifications.Insert(n)
if err != nil {
c.Fatalf("Can't insert document: %v\n", err)
}
}
示例2: Save
func (this *Article) Save() error {
this.Id = bson.NewObjectId()
if len(this.Parent) == 0 {
if err := save(articleColl, this, true); err != nil {
return errors.NewError(errors.DbError, err.Error())
}
return nil
}
if !bson.IsObjectIdHex(this.Parent) {
return errors.NewError(errors.InvalidMsgError)
}
update := bson.M{
"$push": bson.M{
"reviews": this.Id.Hex(),
},
"$inc": bson.M{
"review_count": 1,
},
}
if this.Type == ArticleCoach {
update = bson.M{
"$addToSet": bson.M{
"coaches": this.Author,
},
"$inc": bson.M{
"coach_review_count": 1,
},
}
}
f := func(c *mgo.Collection) error {
runner := txn.NewRunner(c)
ops := []txn.Op{
{
C: articleColl,
Id: this.Id,
Assert: txn.DocMissing,
Insert: this,
},
{
C: articleColl,
Id: bson.ObjectIdHex(this.Parent),
Assert: txn.DocExists,
Update: update,
},
}
return runner.Run(ops, bson.NewObjectId(), nil)
}
if err := withCollection("comment_tx", &mgo.Safe{}, f); err != nil {
log.Println(err)
return errors.NewError(errors.DbError, err.Error())
}
return nil
}
示例3: main
func main() {
var (
mongoSession *mgo.Session
database *mgo.Database
collection *mgo.Collection
err error
)
if mongoSession, err = mgo.Dial("localhost"); err != nil {
panic(err)
}
database = mongoSession.DB("mgo_examples_05")
collection = database.C("todos")
var todos []Todo
todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "First task for today", Created: time.Now(), Due: time.Now().Add(time.Hour * 24)})
todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Second task for today", Created: time.Now(), Due: time.Now()})
todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Third task for today", Created: time.Now(), Due: time.Now()})
todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Fourth task for today", Created: time.Now(), Due: time.Now()})
todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Fifth task for today", Created: time.Now(), Due: time.Now()})
for _, todo := range todos {
if _, err = collection.UpsertId(todo.Id, &todo); err != nil {
panic(err)
}
}
// START OMIT
pipeline := []bson.M{
{"$group": bson.M{
"_id": bson.M{"$dayOfYear": "$d"},
"count": bson.M{"$sum": 1},
}},
}
var (
result TodoDueCounts
results []TodoDueCounts
)
iter := collection.Pipe(pipeline).Iter()
for {
if iter.Next(&result) {
results = append(results, result)
} else {
break
}
}
err = iter.Err()
if err != nil {
panic(err)
}
// END OMIT
fmt.Printf("%# v", pretty.Formatter(results))
}
示例4: get_decks
func get_decks() []Deck {
c := make(chan []int32)
go Get_winner_list(c)
go Get_winner_list(c)
go Get_loser_list(c)
go Get_loser_list(c)
w, x, y, z := <-c, <-c, <-c, <-c
d1 := Deck{bson.NewObjectId(), w}
d2 := Deck{bson.NewObjectId(), x}
d3 := Deck{bson.NewObjectId(), y}
d4 := Deck{bson.NewObjectId(), z}
return []Deck{d1, d2, d3, d4}
}
示例5: NewPoint
func NewPoint(title, location, location_index string,
userid bson.ObjectId) *Point {
point := &Point{
ID: bson.NewObjectId(),
Title: title,
Location: location,
Location_index: location_index,
UserId: userid,
Date: time.Now(),
Img: "/apps/eating/imgs/" + bson.NewObjectId().Hex(),
}
return point
}
示例6: main
func main() {
logout := log.New(os.Stdout, "MGO: ", log.Lshortfile)
mgo.SetLogger(logout)
mgo.SetDebug(false)
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
db := session.DB("bookdb")
cbooks := db.C("bookcoll")
cauthors := db.C("authorcoll")
aids := []bson.ObjectId{bson.NewObjectId(), bson.NewObjectId()}
authors := []Author{{
aids[0],
"Author 1",
}, {
aids[1],
"Author 2",
}}
cauthors.Insert(authors[0])
cauthors.Insert(authors[1])
// Insert some books
mine := Book{
bson.NewObjectId(),
"Gang of four thingy",
aids,
}
cbooks.Insert(&mine)
var assembl []AssembledBooks
cauthors.Find(bson.M{}).All(&assembl)
str1, _ := json.MarshalIndent(assembl, "", " ")
fmt.Printf("%s\n", str1)
var allauthors []Author
cauthors.Find(bson.M{}).All(&allauthors)
str, _ := json.MarshalIndent(allauthors, "", " ")
fmt.Printf("%s\n", str)
var allbooks []Book
cbooks.Find(bson.M{}).All(&allbooks)
str, _ = json.MarshalIndent(allbooks, "", " ")
fmt.Printf("%s\n", str)
fmt.Println("Dropping all collections...")
cauthors.DropCollection()
cbooks.DropCollection()
fmt.Println("Done")
}
示例7: 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{}
}
示例8: Save
func (m *MongoService) Save(collection string, docId string, doc models.MongoModel) (info *mgo.ChangeInfo, err error) {
if docId == "" {
docId = bson.NewObjectId().Hex()
doc.SetId(docId)
}
return m.getCollection(collection).UpsertId(docId, doc)
}
示例9: newArticleHandler
// URL: /article/new
// 新建文章
func newArticleHandler(w http.ResponseWriter, r *http.Request) {
var categories []ArticleCategory
c := DB.C("articlecategories")
c.Find(nil).All(&categories)
var choices []wtforms.Choice
for _, category := range categories {
choices = append(choices, wtforms.Choice{Value: category.Id_.Hex(), Label: category.Name})
}
form := wtforms.NewForm(
wtforms.NewHiddenField("html", ""),
wtforms.NewTextField("title", "标题", "", wtforms.Required{}),
wtforms.NewTextField("original_source", "原始出处", "", wtforms.Required{}),
wtforms.NewTextField("original_url", "原始链接", "", wtforms.URL{}),
wtforms.NewSelectField("category", "分类", choices, ""),
)
if r.Method == "POST" && form.Validate(r) {
user, _ := currentUser(r)
c = DB.C("contents")
id_ := bson.NewObjectId()
html := form.Value("html")
html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1)
categoryId := bson.ObjectIdHex(form.Value("category"))
err := c.Insert(&Article{
Content: Content{
Id_: id_,
Type: TypeArticle,
Title: form.Value("title"),
CreatedBy: user.Id_,
CreatedAt: time.Now(),
},
Id_: id_,
CategoryId: categoryId,
OriginalSource: form.Value("original_source"),
OriginalUrl: form.Value("original_url"),
})
if err != nil {
fmt.Println("newArticleHandler:", err.Error())
return
}
http.Redirect(w, r, "/a/"+id_.Hex(), http.StatusFound)
return
}
renderTemplate(w, r, "article/form.html", map[string]interface{}{
"form": form,
"title": "新建",
"action": "/article/new",
"active": "article",
})
}
示例10: NewContext
func NewContext(req *http.Request) (*Context, error) {
sess, err := store.Get(req, COOKIE_NAME)
ctx := &Context{
Database: db_session.Clone().DB(database),
Session: sess,
Data: make(map[string]interface{}),
}
if err != nil { // if the above is still an error
return ctx, err
}
//try to fill in the user from the session
if uid, ok := sess.Values["user"].(bson.ObjectId); ok {
e := ctx.C("users").Find(bson.M{"_id": uid}).One(&ctx.User)
if ctx.User != nil {
ctx.User.Password = []byte{}
ctx.User.BirthDate = ctx.User.BirthDate.UTC()
}
if e != nil {
Log("error finding user for cookie uid: ", err.Error())
}
}
if _, ok := sess.Values["csrf_token"].(string); !ok {
ctx.Session.Values["csrf_token"] = bson.NewObjectId().Hex()
}
return ctx, err
}
示例11: newUser
// newUser create an *auth.User without save it to database.
// Its set an BSON ObjectID and check email,password.
func (m *MgoUserManager) newUser(email, pwd string, app bool) (*auth.User, error) {
if !m.Formater.EmailValidate(email) {
return nil, auth.ErrInvalidEmail
}
if !m.Formater.PasswordValidate(pwd) {
return nil, auth.ErrInvalidPassword
}
u := &auth.User{}
u.Id = bson.NewObjectId()
u.Email = email
u.LastActivity = time.Now()
u.Info.JoinDay = u.LastActivity
p, err := auth.HashPwd(pwd)
if err != nil {
return nil, err
}
u.Pwd = p
u.Approved = app
if !app {
u.ConfirmCodes = map[string]string{
"activate": base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(64)),
}
}
return u, nil
}
示例12: adminNewArticleCategoryHandler
// URL: /admin/article_category/new
// 新建文章分类
func adminNewArticleCategoryHandler(handler Handler) {
form := wtforms.NewForm(
wtforms.NewTextField("name", "名称", "", wtforms.Required{}),
)
if handler.Request.Method == "POST" {
if !form.Validate(handler.Request) {
renderTemplate(handler, "article_category/new.html", ADMIN, map[string]interface{}{"form": form})
return
}
c := handler.DB.C(ARTICLE_CATEGORIES)
var category ArticleCategory
err := c.Find(bson.M{"name": form.Value("name")}).One(&category)
if err == nil {
form.AddError("name", "该名称已经有了")
renderTemplate(handler, "article_category/new.html", ADMIN, map[string]interface{}{"form": form})
return
}
err = c.Insert(&ArticleCategory{
Id_: bson.NewObjectId(),
Name: form.Value("name"),
})
if err != nil {
panic(err)
}
http.Redirect(handler.ResponseWriter, handler.Request, "/admin/article_category/new", http.StatusFound)
}
renderTemplate(handler, "article_category/new.html", ADMIN, map[string]interface{}{"form": form})
}
示例13: commentAnArticleHandler
// URL: /a/{articleId}/comment
// 评论文章
func commentAnArticleHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
vars := mux.Vars(r)
articleId := vars["articleId"]
user, ok := currentUser(r)
if !ok {
http.Redirect(w, r, "/a/"+articleId, http.StatusFound)
return
}
content := r.FormValue("content")
html := r.FormValue("html")
html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1)
Id_ := bson.NewObjectId()
now := time.Now()
comment := Comment{
Id_: Id_,
UserId: user.Id_,
Markdown: content,
Html: template.HTML(html),
CreatedAt: now,
}
c := db.C("articles")
c.Update(bson.M{"_id": bson.ObjectIdHex(articleId)}, bson.M{"$addToSet": bson.M{"comments": comment}})
http.Redirect(w, r, "/a/"+articleId, http.StatusFound)
}
}
示例14: SaveUserMetaData
func (u *UserMetaData) SaveUserMetaData() RD.ReturnData {
returnData := RD.ReturnData{}
dbSession := Connection.GetDBSession()
dbSession.SetMode(mgo.Monotonic, true)
dataBase := strings.SplitAfter(os.Getenv("MONGOHQ_URL"), "/")
c := dbSession.DB(dataBase[3]).C("jove")
u.Id = bson.NewObjectId()
u.Created_on = time.Now()
err := c.Insert(u)
if err != nil {
log.Print(err.Error())
returnData.ErrorMsg = err.Error()
returnData.Success = false
returnData.Status = "422"
} else {
returnData.Success = true
jsonData, _ := json.Marshal(&u)
returnData.JsonData = jsonData
returnData.Status = "201"
}
return returnData
}
示例15: NameToID
// NameToID - Converts name to ObjectId if its one.
// If `create` is true and name is empty it creates new id and `created` is true.
func NameToID(name interface{}, create bool) (id interface{}, created bool) {
// If create is true and name is empty - create new id
if create {
// If name is nil or empty string
if n, ok := name.(string); name == nil || ok && n == "" {
id = bson.NewObjectId()
created = true
return
}
}
// Try to cast name to ObjectId
var ok bool
if id, ok = name.(bson.ObjectId); ok {
return
}
// By default id is a name
id = name
// If name is ObjectIdHex convert it
if n, ok := name.(string); ok && bson.IsObjectIdHex(n) {
id = bson.ObjectIdHex(n)
}
return
}