我正在使用官方 mongodb-go-driver 从 Go Web 服务器中的 MongoDB 图集获取数据。我正在使用 json.Marshal 转换为 json。但某些字段的所有值都变为零。
package main
import (
"context"
"fmt"
"log"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
var c = GetClient()
type PlantData struct {
Minute int `json:"minute"`
Date int `json:"date"`
Moisture1 int `json:"moisture_1"`
Hour int `json:"hour"`
Month int `json:"month"`
Year int `json:"year"`
Humidity1 float64 `json:"humidity_1"`
Temperature1 float64 `json:"temperature_1"`
}
func GetClient() *mongo.Client {
clientOptions := options.Client().ApplyURI("MY_MONGODB_URI")
client, err := mongo.NewClient(clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Connect(context.Background())
if err != nil {
log.Fatal(err)
}
return client
}
func ReturnAllPlantsData(client *mongo.Client, filter bson.M) []*PlantData {
var plantsdata []*PlantData
collection := client.Database("iot").Collection("tomatos")
cur, err := collection.Find(context.TODO(), filter)
if err != nil {
log.Fatal("Error on Finding all the documents", err)
}
for cur.Next(context.TODO()) {
var plantdata PlantData
err = cur.Decode(&plantdata)
if err != nil {
log.Fatal("Error on Decoding the document", err)
}
plantsdata = append(plantsdata, &plantdata)
}
return plantsdata
}
func getting(g *gin.Context) {
plantsdatas := ReturnAllPlantsData(c, bson.M{})
ans, _ := json.Marshal(plantsdatas)
fmt.Println(string(ans))
c.String(200, string(ans))
}
守候你守候我
相关分类