-
Type: Bug
-
Resolution: Fixed
-
Priority: Major - P3
-
Affects Version/s: 1.11.2
-
Component/s: None
-
None
-
Not Needed
-
Summary
Reading a document from database into a struct with a map[primitive.ObjectID]interface{} give an error if the interface value is an object
Please provide the version of the driver. If applicable, please provide the MongoDB server version and topology (standalone, replica set, or sharded cluster).
Tested on:
Ubuntu server 22 mongod --version:
db version v6.0.4
Build Info: {
"version": "6.0.4",
"gitVersion": "44ff59461c1353638a71e710f385a566bcd2f547",
"openSSLVersion": "OpenSSL 1.1.1f 31 Mar 2020",
"modules": [],
"allocator": "tcmalloc",
"environment":
}
Windows 11 mongod --version
db version v6.0.0
Build Info: {
"version": "6.0.0",
"gitVersion": "e61bf27c2f6a83fed36e5a13c008a32d563babe2",
"modules": [],
"allocator": "tcmalloc",
"environment":
}
How to Reproduce
func NewDB(host string, port string, dbName string) (db *DB) { db = new(DB) db.DbName = dbName db.Host = host db.Port = port db.mongoUrl = "mongodb://" + host + ":" + port return db } type DB struct { DbName string Host string Port string mongoUrl string client *mongo.Client } func (d *DB) Connect() (err error) { log.Println("connecting to: " + d.mongoUrl) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() d.client, err = mongo.Connect(ctx, options.Client().ApplyURI(d.mongoUrl)) return err } func (d *DB) Disconnect() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _ = d.client.Disconnect(ctx) } func (d *DB) FindOne(collection string, query interface{}, doc interface{}) (found bool, err error) { coll := d.client.Database(d.DbName).Collection(collection) ctx := context.Background() err = coll.FindOne(ctx, query).Decode(doc) if err == mongo.ErrNoDocuments { return false, nil } return err == nil, err } func (d *DB) Insert(collection string, doc interface{}) (err error) { coll := d.client.Database(d.DbName).Collection(collection) ctx := context.Background() _, err = coll.InsertOne(ctx, doc) return err } func main() { db := mongo.NewDB("localhost", "27017", "testdb") err := db.Connect() if err != nil { panic(err) } defer db.Disconnect() item := &struct { A map[primitive.ObjectID]interface{} `json:"foo" bson:"foo"` }{} jsonData := "{ \"foo\" : {\"63ea2082b1ce23422a8bf9ca\" : { \"bar\" : \"\" } } }" err = json.Unmarshal([]byte(jsonData), item) if err != nil { fmt.Println("json unmarshal err", err.Error()) } err = db.Insert("test", item) if err != nil { fmt.Println("db insert err", err.Error()) } _, err = db.FindOne("test", bson.M{}, item) if err != nil { fmt.Println("db find err", err.Error()) } }
console:
db find error decoding key foo.63ea2082b1ce23422a8bf9ca: the provided hex string is not a valid ObjectID
- related to
-
GODRIVER-1330 Document interface{} unmarshalling behavior
- Closed