Hello, I am replacing the globalsign/mgo by mongo-driver. I got a problem when I replacing ensureIndex in mgo by CreateIndex in mongo-driver.
One of the collections has an index created by mgo with default name (without setting the name of the index when create it), for example, in mgo the index is created as:
err = session.DB("").C("place").EnsureIndex(mgo.Index{
Key: []string{"$2dsphere:location", "user_id"},
and I replace by the code below:
secondIndex := mongo.IndexModel{
Keys: bson.M{"location": "2dsphere", "user_id": 1},
}
if _, err := db.Collection("place").Indexes().CreateOne(context.TODO(), secondIndex); err != nil {
return err
}
when I run the code I will get error:
panic: (IndexKeySpecsConflict) Index must have unique name.The existing index: { v: 2, key: { location: “2dsphere”, user_id: 1 }, name: “location_2dsphere_user_id_1”, ns: “place”, 2dsphereIndexVersion: 3 } has the same name as the requested index: { v: 2, key: { user_id: 1, location: “2dsphere” }, name: “location_2dsphere_user_id_1”, ns: place", 2dsphereIndexVersion: 3 }
For the other indexes created with a name, I can SetName in IndexOption (with the same name as mgo) and no such error.
The database has been running on product server, so I want to skip the IndexKeySpecsConflict error and keep going forward, i.e.
if _, err := db.Collection(place.Namespace).Indexes().CreateOne(context.TODO(), secondIndex); err != nil {
if !strings.Contains(err.Error(), "IndexKeySpecsConflict") {
return err
}
}
is that a correct way? any other suggestions?
Thanks for your help!
James