直接连接到副本集时,updateOne返回“没有主服务器”错误

时间:2019-08-01 11:16:40

标签: mongo-go

将副本集直接设置为true时,

updateOne方法将抛出“ no master”错误。我该怎么做以确保在更改数据库数据期间mongo-go-driver连接到主节点?

mongo-go-driver版本:https://github.com/mongodb/mongo-go-driver/releases/tag/v1.0.4

连接代码:

func Start() {
    var err error
    credential := options.Credential{
        Username:   db.User,
        Password:   db.Passwd,
        AuthSource: db.Database,
    }
    timeout := 10 * time.Second

    clientOptions := options.Client().SetAuth(credential).SetDirect(true).
        SetReadPreference(readpref.Primary()).
        SetWriteConcern(writeconcern.New(writeconcern.WMajority())).
        SetRetryWrites(true).
        SetReplicaSet("rs0").
        SetConnectTimeout(timeout).ApplyURI(db.Addrs)

    ctx, cancel := context.WithTimeout(context.TODO(), timeout)
    defer cancel()
    client, err = mongo.Connect(ctx, clientOptions)
    if err != nil {
        logger.Fatal("connect to mongodb fail", logger.String("err", err.Error()))
    }

    err = client.Ping(ctx, readpref.Primary())
    if err != nil {
        logger.Fatal("ping mongodb server fail", logger.String("err", err.Error()))
    } else {
        logger.Info("connect to mongodb success")
    }

}

这样的更新方法:

func updateOne(filter, updated interface{}, upsert bool) (*mongo.UpdateResult, error) {
    collection := GetDefaultDatabase().Collection(d.Name())
    updateOptions := options.UpdateOptions{
        Upsert: &upsert,
    }
    return collection.UpdateOne(context.TODO(), filter, updated, &updateOptions)
}

调用updateOne更新记录时,有时会成功,但有时会引发如下错误:

    update_test.go:24: (NotMaster) not master

0 个答案:

没有答案