本文整理汇总了Golang中labix/org/v2/mgo.Session.DB方法的典型用法代码示例。如果您正苦于以下问题:Golang Session.DB方法的具体用法?Golang Session.DB怎么用?Golang Session.DB使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类labix/org/v2/mgo.Session
的用法示例。
在下文中一共展示了Session.DB方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Handler
// Handler returns a http.Handler
func Handler(path string, dbsess *mgo.Session, tmpl *view.View) *handler {
h := &handler{}
h.dbsess = dbsess
h.tmpl = tmpl
h.path = path
h.initSubRoutes()
h.notifer = membership.NewSMTPNotificater(
CONFIG.Get("smtp_email").(string),
CONFIG.Get("smtp_pass").(string),
CONFIG.Get("smtp_addr").(string),
int(CONFIG.Get("smtp_port").(float64)),
)
dbsess.DB(DBNAME).C("toysSession").EnsureIndex(mgo.Index{
Key: []string{"lastactivity"},
ExpireAfter: 7200 * time.Second,
})
dbsess.DB(DBNAME).C("toysUser").EnsureIndex(mgo.Index{
Key: []string{"email"},
Unique: true,
})
return h
}
示例2: main
func main() {
var (
mongoSession *mgo.Session
database *mgo.Database
collection *mgo.Collection
changeInfo *mgo.ChangeInfo
err error
)
if mongoSession, err = mgo.Dial("localhost"); err != nil {
panic(err)
}
database = mongoSession.DB("mgo_examples_03")
collection = database.C("todos")
// START OMIT
var todo = Todo{
Id: bson.NewObjectId(),
Task: "Demo mgo",
Created: time.Now(),
}
// This is a shortcut to collection.Upsert(bson.M{"_id": todo.id}, &todo)
if changeInfo, err = collection.UpsertId(todo.Id, &todo); err != nil {
panic(err)
}
// END OMIT
fmt.Printf("Todo: %# v", pretty.Formatter(todo))
fmt.Printf("Change Info: %# v", pretty.Formatter(changeInfo))
}
示例3: read_mongodb_static_size
func read_mongodb_static_size(f *IOFilterProtocol, session *mgo.Session) bool {
disk_usage := &f.disk_usage
var stats bson.M
var temp int
admindb := session.DB("admin")
// NOTE: admindb.Login is not necessary if we connect to mongodb
// through 'localhost'
err := admindb.Run(bson.D{{"dbStats", 1}, {"scale", 1}}, &stats)
if err != nil {
logger.Error("Failed to get database %s stats [%s].", "admin", err)
return false
}
if !parse_dbstats(stats["nsSizeMB"], &temp) {
logger.Error("Failed to read admin_namespace_size.")
return false
}
admin_namespace_size := uint64(temp * 1024 * 1024)
disk_usage.static_size += admin_namespace_size
if !parse_dbstats(stats["fileSize"], &temp) {
logger.Error("Failed to read admin_data_file_size.")
return false
}
admin_data_file_size := uint64(temp)
disk_usage.static_size += admin_data_file_size
logger.Debug("Get static disk files size %d.", disk_usage.static_size)
return true
}
示例4: processServerSendUsers
func processServerSendUsers(m map[string]interface{}, session *mgo.Session) {
log.Println("PARSING server_send_users")
// wholesale replace users collection
log.Println("wholesale replace users collection")
c := session.DB("landline").C("Users")
c.RemoveAll(bson.M{})
for k, v := range m["users"].([]interface{}) {
log.Println(k)
object := v.(map[string]interface{})
// create object
object_map := make(map[string]interface{})
object_map["encrypted_kek"] = object["encrypted_kek"].(string)
object_map["encrypted_rsa_private"] = object["encrypted_rsa_private"].(string)
object_map["hashed_password"] = object["hashed_password"].(string)
object_map["rsa_public"] = object["rsa_public"].(string)
object_map["username"] = object["username"].(string)
err := c.Insert(object_map)
if err != nil {
panic(err)
}
}
}
示例5: Router
func Router(session *mgo.Session) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
user_agent := new(ua.UserAgent)
user_agent.Parse(req.Header.Get("User-Agent"))
url := req.FormValue("url")
engine_name, engine_version := user_agent.Engine()
browser_name, browser_version := user_agent.Browser()
url_document := &URL{
Date: time.Now(),
Uri: url,
Mobile: user_agent.Mobile(),
Bot: user_agent.Bot(),
Mozilla: user_agent.Mozilla(),
Platform: user_agent.Platform(),
Os: user_agent.OS(),
EngineName: engine_name,
EngineVersion: engine_version,
BrowserName: browser_name,
BrowserVersion: browser_version,
}
c := session.DB("goanywhere").C("urls")
err := c.Insert(url_document)
if err != nil {
panic(err)
}
http.Redirect(w, req, url, http.StatusFound)
}
}
示例6: resetAdminPasswordAndFetchDBNames
// resetAdminPasswordAndFetchDBNames logs into the database with a
// plausible password and returns all the database's db names. We need
// to try several passwords because we don't know what state the mongo
// server is in when Reset is called. If the test has set a custom
// password, we're out of luck, but if they are using
// DefaultStatePassword, we can succeed.
func resetAdminPasswordAndFetchDBNames(session *mgo.Session) ([]string, bool) {
// First try with no password
dbnames, err := session.DatabaseNames()
if err == nil {
return dbnames, true
}
if !isUnauthorized(err) {
panic(err)
}
// Then try the two most likely passwords in turn.
for _, password := range []string{
DefaultMongoPassword,
utils.UserPasswordHash(DefaultMongoPassword, utils.CompatSalt),
} {
admin := session.DB("admin")
if err := admin.Login("admin", password); err != nil {
logger.Infof("failed to log in with password %q", password)
continue
}
dbnames, err := session.DatabaseNames()
if err == nil {
if err := admin.RemoveUser("admin"); err != nil {
panic(err)
}
return dbnames, true
}
if !isUnauthorized(err) {
panic(err)
}
logger.Infof("unauthorized access when getting database names; password %q", password)
}
return nil, false
}
示例7: SaveModel
// Save the DataModel to DataStore
func SaveModel(mgo_db string, m DataModel, conn *mgo.Session) (err error) {
if conn == nil {
conn, err = MgoConnGet(mgo_db)
if err != nil {
return
}
defer conn.Close()
}
if conn != nil {
bsonMid := m.MidGet()
c := conn.DB(mgo_db).C(m.Type())
//Debug("SAVING ", mgo_db, " type=", m.Type(), " Mid=", bsonMid)
if len(bsonMid) < 5 {
m.MidSet(bson.NewObjectId())
if err = c.Insert(m); err != nil {
Log(ERROR, "MGOU ERROR on insert ", err, " TYPE=", m.Type(), " ", m.MidGet())
} else {
//Log(DEBUG, "successfully inserted!!!!!! ", m.MidGet(), " oid=", m.OidGet())
}
} else {
// YOU MUST NOT SEND Mid "_id" to Mongo
mid := m.MidGet()
m.MidSet("") // omitempty means it doesn't get sent
if err = c.Update(bson.M{"_id": bson.ObjectId(bsonMid)}, m); err != nil {
Log(ERROR, "MGOU ERROR on update ", err, " ", bsonMid, " MID=?", m.MidGet())
}
m.MidSet(mid)
}
} else {
Log(ERROR, "MGOU Nil connection")
return errors.New("no db connection")
}
return
}
示例8: Insert
// Save the DataModel to DataStore
func Insert(mgo_db string, m DataModel, conn *mgo.Session) (err error) {
if conn == nil {
conn, err = MgoConnGet(mgo_db)
if err != nil {
return
}
defer conn.Close()
}
if conn != nil {
c := conn.DB(mgo_db).C(m.Type())
if len(m.MidGet()) == 0 {
m.MidSet(bson.NewObjectId())
}
if err = c.Insert(m); err != nil {
Log(ERROR, "MGOU ERROR on insert ", err, " TYPE=", m.Type(), " ", m.MidGet())
} else {
//Log(DEBUG, "successfully inserted!!!!!! ", m.MidGet(), " oid=", m.OidGet())
}
} else {
Log(ERROR, "MGOU Nil connection")
return errors.New("no db connection")
}
return
}
示例9: lastDocument
func lastDocument(session *mgo.Session) {
var m bson.M
coll := session.DB(mongoDb).C(mongoColl)
coll.Find(nil).Sort("-_id").One(&m)
js, _ := json.MarshalIndent(&m, "", " ")
fmt.Println(string(js))
}
示例10: clientDiffRequest
func clientDiffRequest(wsConn *websocket.Conn, session *mgo.Session) {
// init client_diff_request
response_map := make(map[string]interface{})
response_map["action"] = "client_diff_request"
// find syncable object uuids
cb := session.DB("landline").C("SyncableObjects")
var m_result []map[string]interface{}
err := cb.Find(bson.M{}).All(&m_result)
if err != nil {
log.Println(err)
} else {
// objects that the clients knows, but the server may not
object_uuids := make(map[string]interface{})
// loop results
for u, result := range m_result {
_ = u
object_uuids[result["uuid"].(string)] = result["time_modified_since_creation"]
}
response_map["object_uuids"] = object_uuids
// send it over websocket
wsConn.WriteJSON(response_map)
log.Println("Wrote message:")
jsonString, _ := json.Marshal(response_map)
log.Println(string(jsonString))
}
}
示例11: startSession
// startSession will create a new document in the sessions collection and return the _id
func startSession(session *mgo.Session, username string) (*SessionId, error) {
c := session.DB(database).C(sessions)
sessionId := &SessionId{Id: bson.NewObjectId(), Username: username}
if err := c.Insert(sessionId); err != nil {
return nil, err
}
return sessionId, nil
}
示例12: getDB
func getDB(session *mgo.Session) *mgo.Database {
var db *mgo.Database
if fDev {
db = session.DB("dev")
} else {
db = session.DB("prod")
}
return db
}
示例13: collection
func collection(m interface{}, s *mgo.Session) *mgo.Collection {
typ := reflect.TypeOf(m)
i := strings.LastIndex(typ.String(), ".") + 1
n := typ.String()[i:len(typ.String())]
db := revel.Config.StringDefault("db.name", "helix")
c := revel.Config.StringDefault("db.collection."+n, n)
return s.DB(db).C(c)
}
示例14: UpdateUserByM
func UpdateUserByM(session *mgo.Session, m bson.M, obj interface{}) error {
uc := session.DB(DbName).C(CollectionName)
err := uc.Update(m, obj)
if err == nil {
fmt.Println("update ", obj, " ok")
} else {
fmt.Println("update ", obj, "failed :", err)
}
return err
}
示例15: DeleteUserByM
func DeleteUserByM(session *mgo.Session, host *User, m bson.M) error {
uc := session.DB(DbName).C(CollectionName)
err := uc.Remove(m)
if err != nil {
fmt.Println(fmt.Sprintf("Cannot delete user by %s", m))
} else {
fmt.Println(fmt.Sprintf("delete user by %s", m))
}
return err
}