duanbozhong9689 2019-09-24 08:04
浏览 358
已采纳

为什么我从mongodb获取json中某个字段的所有零值?

I'm fetching my data from MongoDB atlas in a Go web Server using the official mongodb-go-driver. I'm using json.Marshal to convert to json. but all values of certain fields becomes Zero.

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()
}

My Expected Output:

[{
    "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
}]

Actual Result:

[{
    "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
}]

Values of minute,hour,date,month and year are Correct and Unchanged but all the values of moisture, humidity and temperature becomes zero.

  • 写回答

1条回答 默认 最新

  • douhuang5331 2019-09-24 08:23
    关注

    You have to use bson tags when marshalling from / to MongoDB. json tags are for the encoding/json package, and they are not used (ignored) by the Mongo driver.

    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"`
    }
    

    If bson tags are missing from your struct fields, the default name used in MongoDB will be the struct field name starting with lowercased letters, that's why some (most) of the fields were matched but not Moisture1 (it differs more than just the capital first letter from moisture_1).

    If you also want to use the encoding/json package with this struct, you may provide both:

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能