Answer the question
In order to leave comments, you need to log in
How to correctly insert an object with an ObjectID field into MongoDB (Golang mongo-driver)?
There is a structure with a primitive.ObjectID field, which must be assigned by the DBMS itself.
type Indicator struct {
Id primitive.ObjectID `bson:"_id"`
Name string
Ticker string
Options map[string]interface{}
Subscribers []string
}
testIndicator := db.Indicator{
Name: "testLevel",
Ticker: "AAPL",
Options: map[string]interface{}{
"price": 238.0,
"update_rate": "30min",
},
Subscribers: []string{"testsub1", "testsub2"},
}
res, err := indicatorCollection.InsertOne(ctx, testIndicator)
if err != nil {
t.Error(err)
}
fmt.Println(res.InsertedID) // выводит: ObjectID("000000000000000000000000")
Answer the question
In order to leave comments, you need to log in
That's right, you send such an _id when sending, because you have this value in the structure by default.
There are several options for resolving the issue:
1) Use different structures for receiving and sending, where there will be no _id field in the structure for insertion, then the monga itself will set the value for id.
2) Or generate id on the client through primitive. NewObjectID ()
in your case:
testIndicator := db.Indicator{
ID: primitive.NewObjectID(),
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question