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.Record { var attach models.Record 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.Record) { _, err := global.GLO_COLLECTION.InsertOne(context.TODO(), attach) if err != nil { log.Fatal("插入出错: ", err) } } //ListAttach 查询文档 func ListAttach() []models.Record { var attachs []models.Record 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.Record err := cur.Decode(&attach) if err != nil { log.Fatal("解码出错: ", err) } attachs = append(attachs, attach) } return attachs } //Find 分页查询 func Find(limit, page int64) (data []models.Record, total int64, err error) { var findOptions *options.FindOptions = &options.FindOptions{} if limit > 0 { findOptions.SetLimit(limit) findOptions.SetSkip((limit * page) - limit) } cur, err := global.GLO_COLLECTION.Find(context.Background(), bson.M{}, findOptions) defer cur.Close(context.Background()) if err != nil { log.Fatal("查询出错: ", err) return } cur.All(context.Background(), &data) // 查询总数 var recordNum int64 recordNum, err = global.GLO_COLLECTION.CountDocuments(context.Background(), bson.M{}) if err != nil { log.Fatal("查询出错: ", err) return } total = recordNum / limit if recordNum%limit != 0 { total++ } return }