Go方法應(yīng)該將任何JSON對(duì)象保存在蒙哥數(shù)據(jù)庫(kù)中。在代碼中,僅保存 ID,而不保存整個(gè)對(duì)象。如何解決這個(gè)問(wèn)題?import ( "context" "encoding/json" "go.mongodb.org/mongo-driver/bson" "net/http")//insert the value to mongoDB without any parsingfunc InsertObjectToDatabase(response http.ResponseWriter, request *http.Request) { //call database and collection currentDatabase := clients.MongoClientForThisMicroservice.Database("APP_MONGO_DB") currentCollection := currentDatabase.Collection("APP_MONGO_DB") //convert structured data to bson bsonBytes, errBsonConvert := bson.Marshal(json.NewDecoder(request.Body)) if errBsonConvert != nil { ErrorResponse(response, errBsonConvert) return } //write values to database _, errInsertDatabase := currentCollection.InsertOne(context.TODO(), bsonBytes) if errInsertDatabase != nil { ErrorResponse(response, errInsertDatabase) return } return}結(jié)果在蒙哥數(shù)據(jù)庫(kù){"_id": { "$oid": "611b754fd413ee180f0a3d0a"}
1 回答

白板的微信
TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
您需要傳遞 Go 值,而不是版本。bson.Marshal()
例如:
var model Model
if err := json.NewDecoder(response.Body).Decode(model); err != nil {
// handle m
}
_, _ = currentCollection.InsertOne(context.TODO(), model)
- 1 回答
- 0 關(guān)注
- 74 瀏覽
添加回答
舉報(bào)
0/150
提交
取消