0

I'm attempting to create nested objects in mongoDB with no luck the format I am trying to achieve is as follows

 "Courses":{
    "Date":{
      "CourseName"  :{
                "hole 1"{

                }
                "hole 2"{

                }
                ...so on until 18 
               }//coursename
             }//date 
          }//courses

I've tried and succeeded with getting the date object within course by doing the following:

u := req.FormValue("username")
co := req.FormValue("course")
d := req.FormValue("date")

ng := nGame{Username: u, Course: co, Dates: d}
cn := courseName{CName: co}
query := bson.M{"username": u}
update := bson.M{"$push": bson.M{"Course": bson.M{ng.Dates: cn}}}  
err = c.Update(query, update)

The date object has the course name inside it what i'm trying to do is make course name another object which then I can insert the hole object.

The Structs i'm using are as follows:

type (
nGame struct {
    Username string
    Course   string
    Location string
    Dates    string
}
)
type (
courseName struct {
    CName string
}
)

1 Answer 1

2

Your described structure, as I understand it, can be represented in Go as follows:

type Hole struct {
    // Whatever you want here
}

type Course struct {
    Hole1 Hole `json:"hole 1"`
    Hole2 Hole `json:"hole 2"`
    // ...
    Hole18 Hole `json:"hole 18"`
}

type Courses struct {
    //  Date       CourseName
    map[string]map[string]Course
}

I would suggest, however, using an 18-element array for your holes, but that's up to you:

type Course struct {
    Holes [18]Hole
}

Then you can instantiate one of these trees as (using a [18]Hole array; adjust accordingly if you use a different implementation):

courses := Courses{
    map[string]map[string]Course{
        "2017-01-01": map[string]Course{
            "Bob's Course": Course{
                [18]Hole{
                    Hole{
                      // Hole 1
                    },
                    Hole{
                      // Hole 2
                    },
                    // ..
                },
            },
        },
    },
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the quick response its much appreciated I'm trying to implement you're structure at the minute but can seem to initialize the structs with data. As for the suggestion I agree you're way is better and more efficient I will be using an array instead.
@coder-noob I have updated the answer with additional information, and a correction to the Courses type.
Thank you for you're help i will go implement this now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.