Exemple #1
0
func TestDocumentManager_Register_InvalidAnnotation(t *testing.T) {
	type City struct {
		Name string `odm:"invalidAnnotation"`
	}
	dm := mongo.NewDocumentManager(nil)
	err := dm.Register("City", new(City))
	test.Fatal(t, err, mongo.ErrInvalidAnnotation)
}
Exemple #2
0
func getDocumentManager(t *testing.T) (dm mongo.DocumentManager, done func()) {

	dm = mongo.NewDocumentManager(getDB(t))
	err := dm.GetDB().DropDatabase()
	test.Fatal(t, err, nil)
	if debug == true || verbose == true {
		dm.SetLogger(test.NewTestLogger(t))
	}
	done = func() {
		dm.GetDB().DropDatabase()
		dm.GetDB().Session.Close()
	}
	return
}
Exemple #3
0
func Example() {

	type Author struct {
		// ID is the mongo id, needs to be set explicitly
		ID bson.ObjectId `bson:"_id,omitempty"`

		// Name is the author's name
		// unfortunatly mgo driver lowercases mongo keys by default
		// so always explicitely set the key name to the field name
		//
		// index(unique:true) creates an unix index on key Name, so
		// there is no duplicates for that key
		Name string `bson:"Name" odm:"index(unique:true)"`
	}

	type Tag struct {
		ID   bson.ObjectId `bson:"_id,omitempty"`
		Name string        `bson:"Name" odm:"index"`
	}

	type Article struct {
		ID bson.ObjectId `bson:"_id,omitempty"`

		// The title of the blog post
		Title string `bson:"Title"`

		// The author of the post, the owning side of the Article/Author relationship
		Author *Author `odm:"referenceOne(targetDocument:Author)"`

		// Article references many tags.
		// cascade tells the document manager to automatically persist related Tags when Article is persisted,
		// it will also automatically remove related tags as well.
		Tags []*Tag `odm:"referenceMany(targetDocument:Tag,cascade:all)"`
	}

	// create a mongodb connection
	session, err := mgo.Dial(os.Getenv("MONGODB_TEST_SERVER"))
	if err != nil {
		log.Println("error connecting to the db", err)
		return
	}
	// select a database
	db := session.DB(os.Getenv("MONGODB_TEST_DB"))
	defer cleanUp(db)

	// create a document manager
	documentManager := mongo.NewDocumentManager(db)

	if debug == true {
		documentManager.SetLogger(test.NewTestLogger(&test.ExampleTester{log.New(os.Stderr, "", log.LstdFlags)}))
	}

	// register the types into the document manager
	if err = documentManager.RegisterMany(map[string]interface{}{
		"Article": new(Article),
		"Author":  new(Author),
		"Tag":     new(Tag),
	}); err != nil {
		log.Println("error registering types", err)
		return
	}
	// create some documents
	author := &Author{Name: "John Doe"}
	programmingTag := &Tag{Name: "programming"}
	article1 := &Article{Title: "Go tiger!", Author: author, Tags: []*Tag{{Name: "go"}, programmingTag}}
	article2 := &Article{Title: "MongoDB", Author: author, Tags: []*Tag{programmingTag}}

	// plan for saving
	// we don't need to explicitly persist Tags since
	// Article type cascade persists tags
	documentManager.Persist(author)
	documentManager.Persist(article1)
	documentManager.Persist(article2)

	// do commit changes
	if err = documentManager.Flush(); err != nil {
		log.Println("error saving documents", err)
		return
	}

	// query the database
	author = new(Author)
	if err = documentManager.FindOne(bson.M{"Name": "John Doe"}, author); err != nil {
		log.Println("error fetching author", err)
		return
	}
	fmt.Println("author's name :", author.Name)

	// query a document by ID
	authorID := author.ID
	author = new(Author)
	if err = documentManager.FindID(authorID, author); err != nil {
		log.Println("error fetching author by id", err)
		return
	}

	// fetch all documents
	articles := []*Article{}
	if err = documentManager.FindAll(&articles); err != nil {
		log.Println("error fetching articles", err)
		return
	}
	fmt.Println("articles length :", len(articles))

	// or query specific documents
	articles = []*Article{}
	if err = documentManager.FindBy(bson.M{"Title": "MongoDB"}, &articles); err != nil {
		log.Println("error fetching articles by title", err)
		return
	}
	fmt.Println("articles length :", len(articles))

	// remove a document
	documentManager.Remove(articles[0])
	if err = documentManager.Flush(); err != nil {
		log.Println("error removing article", err)
		return
	}
	// since removing an article remove the related tags, 'programming' tag
	// should not exist in the db

	tag := new(Tag)
	if err = documentManager.FindOne(bson.M{"Name": "programming"}, tag); err != mgo.ErrNotFound {
		log.Printf("%+v\n", tag)
		log.Println("the error should be : mgo.ErrNotFound, got ", err)
		return
	}

	// use complex queries

	author = new(Author)
	// query one document
	query := documentManager.CreateQuery().
		Find(bson.M{"Name": "John Doe"}).Select(bson.M{"Name": 1})

	if err = query.One(author); err != nil {
		log.Println("Error querying one author", err)
		return
	}
	fmt.Println("name:", author.Name)

	authors := []*Author{}
	// query multiple documents
	query = documentManager.CreateQuery().
		Find(bson.M{"Name": bson.M{"$ne": "Jane Doe"}}).
		Select(bson.M{"ID": 1, "Name": 1}).
		Skip(0).Limit(50).Sort("Name")

	if err = query.All(&authors); err != nil {
		log.Println("Error querying authors", err)
		return
	}
	fmt.Println("authors:", len(authors))
	// Output:
	// author's name : John Doe
	// articles length : 2
	// articles length : 1
	// name: John Doe
	// authors: 1
}