0

I want to insert datastruct like below to MongoDB

{ "rolecode": "DHBK1_ROLE_04", "functioncodelist": [ "DHBK1_FUNC_1", "DHBK1_FUNC_2", ..... "DHBK1_FUNC_n"] "productid": "ABC_Platform", "comid": "DHBK1" }

Here is my code:

package main
import (
    "context"
    "gopkg.in/mgo.v2"
)


func main() {
    insertObj()
}
type CompanyRoleFunction struct {
    Rolecode         string `json:"rolecode"`
    Productid        string `json:"productid"`
    Functioncodelist []string
    Comid string `json:"comid"`
}
func insertObj() {
    session, err := mgo.Dial("mongodb://casuser:[email protected]:27017/users")
    if err != nil {
    panic(err)
    }
    c := session.DB("users").C("company_role_function")
    var companyRoleFunction CompanyRoleFunction
    companyRoleFunction.Rolecode = "DHBK1_ROLE_05"
    companyRoleFunction.Productid = "XYZ_Platform"
    companyRoleFunction.Comid = "DHBK1"
    err = c.Insert(companyRoleFunction)
    if err != nil {
        fmt.Println(err)
    }
}

My code have run but it only insert struct like this (of course, because I don't know how to handle array Functioncodelist )

[![enter image description here][1]][1]

Here is my data, I hope to insert

{"_id":{"$oid":"5ed0c2e2402a000037004c84"},"rolecode":"DHBK1_ROLE_07","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2"],"productid":"ABC_Platform","comid":"DHBK1"}

1 Answer 1

0

It doesn't show up in the database because the document you inserted did not contain any values. Set a value in your go code and it should show up just fine in the database, unless I misinterpreted your question.

...
type Functioncode string
...
companyRoleFunction.Functioncodelist = make(map[string]Functioncode)
...
companyRoleFunction.Functioncodelist["foo"] = "bar"
...

See https://tour.golang.org/moretypes/19 for a quick introduction to go maps.

Sign up to request clarification or add additional context in comments.

4 Comments

I add your code but it show error ".\main.go:61:46: cannot use "bar" (type string) as type Functioncode in assignment". I have add database in my question. Please help me
In your code, Functioncode is an empty struct. Define Functioncode as something sensible that fulfills your needs and set the value accordingly. As far as I can see replacing Functioncode with just string would work fine.
Hi, I have edited my code, I chage functioncodelist to array, I think it will easy. Please help me. Thanks
We're not here to write your code for you. If you want to code in Go, you should at least read and understand the basic tutorials.

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.