Created
March 18, 2015 23:44
-
-
Save lettergram/0e95eeccbff8315a8c37 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Book struct { | |
Title string | |
Author string | |
ISBN string | |
Genre string | |
Id string | |
} | |
// Creates an account and adds it to the Database | |
func CreateBook(book *Book) bool { | |
// Dial up a mongoDB session | |
session, err := mgo.Dial("127.0.0.1:27017/") | |
if err != nil { | |
fmt.Println(err) | |
return false | |
} | |
// Opens the "library" databases, "books" collection | |
c := session.DB("library").C("books") | |
result := Book{} | |
// Search for the bookID, place in result.Id | |
err = c.Find(bson.M{"id": book.Id}).One(&result) | |
if result.Id != "" { | |
// return true because book is present in the database | |
// and we can say, "it's been added" without causing errors | |
return true | |
} | |
// insert the book if it is not already in the database | |
err = c.Insert(*book) | |
if err != nil { | |
return false | |
} | |
// Close session to save resources | |
session.Close() | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment