package dao import ( "context" "go.mongodb.org/mongo-driver/bson" "log" "zggsong.cn/sandstone/server/global" "zggsong.cn/sandstone/server/models" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) const ( MONGOURL = "mongodb://admin:123456@localhost:27017" DATABASE = "test" COLLECTION = "image" ) func init() { clientOptions := options.Client().ApplyURI(MONGOURL) // 连接到MongoDB cli, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } // 检查连接 err = cli.Ping(context.TODO(), nil) if err != nil { log.Fatal(err) } log.Println("Connected to MongoDB!") global.GLO_CLIENT = cli global.GLO_COLLECTION = cli.Database(DATABASE).Collection(COLLECTION) } //GetAttach 添加文档 func GetAttach(key string) models.Attach { var attach models.Attach err := global.GLO_COLLECTION.FindOne(context.TODO(), bson.M{"key": key}).Decode(&attach) if err != nil { log.Fatal("查询出错: ", err) } return attach } //AddAttach 添加文档 func AddAttach(attach *models.Attach) { _, err := global.GLO_COLLECTION.InsertOne(context.TODO(), attach) if err != nil { log.Fatal("插入出错: ", err) } } //ListAttach 查询文档 func ListAttach() []models.Attach { var attachs []models.Attach cur, err := global.GLO_COLLECTION.Find(context.TODO(), bson.M{}) if err != nil { log.Fatal("查询出错: ", err) return attachs } for cur.Next(context.TODO()) { var attach models.Attach err := cur.Decode(&attach) if err != nil { log.Fatal("解码出错: ", err) } attachs = append(attachs, attach) } return attachs }