golang mongodb (mgo) is not inserting docs
Asked Answered
L

1

6

Im having issues with persisting a golang struct in mongodb using mgo.

type AN_Track_Log struct {
    Id                       bson.ObjectId `bson:"_id,omitempty"`
    user_session_id_str      string       `bson:"user_session_id_str"`

    googleanaly_pixel_id_str string `bson:"googleanaly_pixel_id_str"`
    perfaud_pixel_id_str     string `bson:"perfaud_pixel_id_str"`
    site_id_str              string `bson:"site_id_str"`
    metric_str               string `bson:"metric_str"`
    value_str                string `bson:"value_str"`
    event_str                string `bson:"event_str"`
    location_id_str          string `bson:"location_id_str"`
    referer_str              string `bson:"referer_str"`
    track_origin_str         string `bson:"track_origin_str"`
    fingerprint_str          string `bson:"fingerprint_str"`
    ...
}

p_track_log.Id = bson.NewObjectId()
err := p_mongodb_coll.Insert(&p_track_log)

the problem is that when the Insert() call completes, the only thing thats persisted in the DB is an empty doc

{u'_id': ObjectId('561809d20037873154000003')}

I check that the struct fields are indeed set, and not empty. Any ideas as to why this is happening. Hints are appreciated :) thank you

Lauderdale answered 9/10, 2015 at 19:1 Comment(0)
S
10

You need to export the fields by starting the field name with a capital letter.

type AN_Track_Log struct {
  Id                       bson.ObjectId `bson:"_id,omitempty"`
  User_session_id_str      string       `bson:"user_session_id_str"`

  Googleanaly_pixel_id_str string `bson:"googleanaly_pixel_id_str"`
  ...
}
Sennit answered 9/10, 2015 at 19:19 Comment(6)
damn it, right! mgo is an external package :) thank youLauderdale
To build on this - you should name your fields according to Go conventions - UserSessionID or GoogleAnalyPixelID - and use the struct tags (as you have) if your database expects snake_case.Sherrillsherrington
what happens if you want a field with an uppercase letter?Undersexed
@Undersexed The first character must be uppercase. All other characters can be upper or lower.Lapel
so it's not possible to have a field with all lowercase characters?? Isn't this a huge limitation of the library? What is you work with existing data with has fieldnames which are all lower case?Undersexed
The field name in the database can be specified using a field tags. There are no restrictions on the case of the names used in the field tag. The code in this answer uses lowercase field names in the db.Lapel

© 2022 - 2024 — McMap. All rights reserved.