Home >Backend Development >Golang >How to Resolve \'No write concern mode named \'majority\' found\' Error in MongoDB?
Write Concern Error in MongoDB
When inserting data into MongoDB using the majority write concern, it is possible to encounter the error:
No write concern mode named 'majority`' found in replica set configuration
This error occurs because the replica set configuration does not include a write concern mode named majority.
Resolving the Error
To resolve this error, add the majority write concern mode to the replica set configuration. The majority write concern ensures that data is written to a majority of the replica set members before acknowledging the write.
Example Connection String
The following connection string includes the majority write concern:
mongodb+srv://user:[email protected]/DBname?retryWrites=true&w=majority
Modify Database Connection
Update the database connection setup function to add the majority write concern:
import ( "context" "time" "go.mongodb.org/mongo-driver/mongo" ) var DbConn *mongo.Client func SetupDB(conn_str string) { var err error opts := options.Client().ApplyURI(conn_str).SetWriteConcern(options.Majority()) DbConn, err = mongo.NewClient(opts) if err != nil { log.Fatal(err) } ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) err = DbConn.Connect(ctx) if err != nil { log.Fatal(err) } }
Updating Request
Ensure that the InsertOne request is using the updated database connection:
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() result, err := DbConn.Database(dbName).Collection(collectionName).InsertOne(ctx, b)
After making these changes, rerun the application and the error should be resolved.
The above is the detailed content of How to Resolve \'No write concern mode named \'majority\' found\' Error in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!