json - 为什么我从 mongodb 的 json 中的某些字段的值全为零?

标签 json mongodb go mongo-go

我正在使用官方 mongodb-go-driver 从 Go Web 服务器中的 MongoDB map 集获取我的数据。我正在使用 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))
}

func main() {
    err := c.Ping(context.Background(), readpref.Primary())
    if err != nil {
        log.Fatal("Couldn't connect to the database", err)
    } else {
        log.Println("Connected!")
    }

    router := gin.Default()
    router.GET("/data", getting)    
    router.Run()
}

我的预期输出:
[{
    "minute": 3,
    "date": 14,
    "moisture_1": 96,
    "hour": 23,
    "month": "02",
    "year": 2019,
    "humidity_1": 77.2,
    "temperature_1": 22.7
}, {
    "minute": 8,
    "date": 14,
    "moisture_1": 96,
    "hour": 23,
    "month": "02",
    "year": 2019,
    "humidity_1": 78.1,
    "temperature_1": 22.8
}]

实际结果:
[{
    "minute": 3,
    "date": 14,
    "moisture_1": 0,
    "hour": 23,
    "month": "02",
    "year": 2019,
    "humidity_1": 0,
    "temperature_1": 0
}, {
    "minute": 8,
    "date": 14,
    "moisture_1": 0,
    "hour": 23,
    "month": "02",
    "year": 2019,
    "humidity_1": 0,
    "temperature_1": 0
}]

分钟、小时、日期、月份和年份的值正确且未更改
但是湿度、湿度和温度的所有值都变为零。

最佳答案

您必须使用 bson从/到 MongoDB 编码时的标签。 json标签适用于 encoding/json包,并且 Mongo 驱动程序不会使用(忽略)它们。

type PlantData struct {
    Minute       int     `bson:"minute"`
    Date         int     `bson:"date"`
    Moisture1    int     `bson:"moisture_1"`
    Hour         int     `bson:"hour"`
    Month        int     `bson:"month"`
    Year         int     `bson:"year"`
    Humidity1    float64 `bson:"humidity_1"`
    Temperature1 float64 `bson:"temperature_1"`
}

如果 bson结构字段中缺少标签,MongoDB 中使用的默认名称将以小写字母开头的结构字段名称,这就是为什么某些(大多数)字段匹配但不匹配 Moisture1 (它不仅仅不同于 moisture_1 的大写首字母)。

如果您还想使用 encoding/json使用此结构打包,您可以同时提供:
type PlantData struct {
    Minute       int     `bson:"minute" json:"minute"`
    Date         int     `bson:"date" json:"date"`
    Moisture1    int     `bson:"moisture_1" json:"moisture_1"`
    Hour         int     `bson:"hour" json:"hour"`
    Month        int     `bson:"month" json:"month"`
    Year         int     `bson:"year" json:"year"`
    Humidity1    float64 `bson:"humidity_1" json:"humidity_1"`
    Temperature1 float64 `bson:"temperature_1" json:"temperature_1"`
}

关于json - 为什么我从 mongodb 的 json 中的某些字段的值全为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59017731/

相关文章:

go - 读取多部分请求导致意外的 EOF 错误

json - 如何从 get 请求中获取 json 响应而不是 html 响应?

javascript - 如何使用连字符访问 JSON 键

mongodb - 这是将图像直接存储在 MongoDB 而不是服务器端文件夹的优点

java - NoClassDefFoundError 和 ExceptionInitializeError

json - panic : json: cannot unmarshal array into Go value of type main. 结构

javascript显示数组中用户定义的元素

java - 如何将Json反序列化为Map的Map?

json - MongoDB减少嵌套

go - 找不到包 "api/handlers"