Hi i am using mongo and golang according to my use case i want to generate a _id before insertion, for that i am using
bson.NewobjectId()
my struct is somewhat like this
type Device struct {
Id bson.ObjectId `bson:"_id" json:"_id,omitempty"`
UserId string `bson:"userId" json:"userId"`
CategorySlug string `bson:"categorySlug" json:"categorySlug"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
ModifiedAt time.Time `bson:"modifiedAt" json:"modifiedAt"`
BrandId int `bson:"brandId" json:"brandId"`
Category string `bson:"category" json:"category"`
}
when i am using this json request
{
"userId" : "gKn42jJD8uy8ksQpi",
"categorySlug" : "television",
"createdAt" : "2016-08-25T18:47:29.558Z",
"modifiedAt" : "2016-08-25T18:47:29.558Z",
"brandId" : 90,
"category" : "LED TV",
"dateOfPurchase" : "2016-08-25T18:47:29.558Z"
}
and decodes this into device type and after that initialize my id using decode.ID = bson.NewObjectId()
but when i looked into my database the inserted value its strangely in this form
{
"_id" : ObjectId("57bf425a34ce5ee85891b914"),
"0" : {
"_id" : ObjectId("57bf425ae03ec2179a000001"),
"userId" : "gKn42jJD8uy8ksQpi",
"categorySlug" : "television",
"createdAt" : ISODate("2016-08-25T18:47:29.558Z"),
"modifiedAt" : ISODate("2016-08-25T18:47:29.558Z"),
"brandId" : 90,
"category" : "LED TV",
"dateofpurchase" : ISODate("2016-08-25T18:47:29.558Z")
}
}
I dont know the reason why is this happening so i want my data in a proper mongo document . Please help me let know why is this thing happening and new _id is getting generated
I'm pretty sure it's something with your other code. Next code (that uses your data structure) correctly inserts single entries.
package main
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"time"
)
type Device struct {
Id bson.ObjectId `bson:"_id" json:"_id,omitempty"`
UserId string `bson:"userId" json:"userId"`
CategorySlug string `bson:"categorySlug" json:"categorySlug"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
ModifiedAt time.Time `bson:"modifiedAt" json:"modifiedAt"`
BrandId int `bson:"brandId" json:"brandId"`
Category string `bson:"category" json:"category"`
}
func main() {
session, err := mgo.Dial("mongodb://127.0.0.1:27017/so")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("so").C("insrt")
doc := Device{
Id: bson.NewObjectId(),
UserId: "gKn42jJD8uy8ksQpi",
CategorySlug: "television",
CreatedAt: time.Now(),
ModifiedAt: time.Now(),
BrandId: 90,
Category: "LED TV",
}
err = c.Insert(doc)
if err != nil {
panic(err)
}
}