Rread data from slice struct

20 views
Skip to first unread message

Phong Vo

unread,
Nov 4, 2019, 11:56:29 AM11/4/19
to mongodb-go-driver
I want to make the replationships one-many in mongo-db

I created 3 structs

User struct {
        ID               primitive.ObjectID          `json:"ID" bson:"_id"`
        UserName         string               `json:"UserName"`
        Profile          Profile              `json:"Profile"`
        Connections      []Connection        `json:"Connections",bson:"connections"`       
    }
Connection  struct {
        OrganisationID primitive.ObjectID `json:"OrganisationID" bson:"organisationid"`
        UpdatedDateUTC string             `json:"UpdatedDateUTC,omitempty"`
    }
Organisation struct {
        ID primitive.ObjectID `json:"ID" bson:"_id"`
}

{ "_id" : ObjectId("5dbd4f46a473a70609b00d76"), "username" : "phong", "updateddateutc" : ISODate("2019-11-02T09:41:27.028Z"), "createdateutc" : "", "connections" : [ { "organisationid" : ObjectId("5dbd4f46a473a70609b00d75"), "updateddateutc" : "" } ] }

I can store the data into mongodb, But when I read data with function findOne(), all most fields can read but the "connections" was return with length is zero.

Could you help to see what happen in my code?





Wan Bachtiar

unread,
Nov 13, 2019, 9:36:41 PM11/13/19
to mongodb-go-driver

Could you help to see what happen in my code?

Hi Phong,

Ignoring some of the missing structs/data on your example i.e. Profile. Given the JSON document sample with the following class mappings:

type User struct 
{
    ID               primitive.ObjectID   `json:"ID" bson:"_id"`
    UserName         string               `json:"UserName"`
    Connections      []Connection        `json:"Connections",bson:"connections"`       
}
type Connection  struct 
{
    OrganisationID primitive.ObjectID `json:"OrganisationID" bson:"organisationid"`
    UpdatedDateUTC string             `json:"UpdatedDateUTC,omitempty"`
}

You should be able to decode Connection as below:

userDoc := User{}
err = collection.FindOne(ctx, bson.M{}).Decode(&userDoc)
fmt.Println(userDoc.Connections)

If you are still encountering issues with this, please provide:

  • MongoDB Go driver version
  • Code snippets (the class maps, the FindOne)

Regards,
Wan.

Phong Vo

unread,
Nov 14, 2019, 4:26:17 AM11/14/19
to mongodb-go-driver
Hi Wan,
Thank for you reply about isuses.

I found the problem from date decode. I define the dates as string but store the ISO date in mongodb.
It will stop decode all the fields after that.

Regards,
Phong
Reply all
Reply to author
Forward
0 new messages