登录
首页 >  Golang >  Go问答

未经授权的错误可能会导致创建索引

来源:stackoverflow

时间:2024-03-04 09:36:27 331浏览 收藏

一分耕耘,一分收获!既然都打开这篇《未经授权的错误可能会导致创建索引》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我正在开发一个使用 go 微服务连接到 azure cosmosdb 的项目。 在开发/阶段环境中,我使用 mongodb api 3.6,用于生产 4.0。

微服务在集合上创建索引。对于开发/阶段环境,一切工作都很好。但在生产中我检索到以下错误:

(未经授权)错误=13,详细信息='响应状态代码不 表示成功,尝试的区域数量:1

我已经检查了连接字符串两次,目前生产数据库没有防火墙规则。

我的代码看起来很熟悉:

package repository

import (
    "go.mongodb.org/mongo-driver/mongo"
    "log"
)

func Collection(db *mongo.Database, c string, indices ...mongo.IndexModel) *mongo.Collection {
    col := db.Collection(c)

    if indices != nil {
        _, err := col.Indexes().CreateMany(ctx, indices)
        if err != nil {
            log.Fatal(err)
        }
    }

    return col
}

// .....

package service

import (
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "repository"
)

col := repository.Collection(db, "my_col", []mongo.IndexModel{
    {
        Keys:    bson.M{"uuid": 1},
        Options: options.Index().SetUnique(true),
    },
}...)

有人知道导致此错误的原因吗?


正确答案


我已联系 microsoft 支持人员,他们的回复如下:

这是具有时间点还原功能的帐户的限制。必须使用唯一索引创建集合。

https://learn.microsoft.com/en-us/azure/cosmos-db/continuous-backup-restore-introduction

您可以使用这样的命令来创建具有已存在的唯一索引的集合(来自 mongo shell、robo3t 或其他客户端)

MongoDB extension commands to manage data in Azure Cosmos DB’s API for MongoDB | Microsoft Docs

例如:

db.runcommand({
  customaction: "createcollection",
  collection: "my_collection",
  shardkey: "my_shard_key",
  offerthroughput: 100,
  indexes: [{key: {_id: 1}, name: "_id_1"}, {key: {a: 1, b: 1}, name:"a_1_b_1", unique: true} ]
})

现在我的代码如下所示:

func Collection(db *mongo.Database, c string, indices []bson.M) *mongo.Collection {
    ctx, cls := context.WithTimeout(context.Background(), time.Second * 15)
    defer cls()

    if cursor, _ := db.ListCollectionNames(ctx, bson.M{"name": c}); len(cursor) < 1 {
        cmd := bson.D{{"customAction", "CreateCollection"}, {"collection", c}}
        if indices != nil {
            cmd = append(cmd, bson.E{Key: "indexes", Value: indices})
        }

        res := db.RunCommand(ctx, cmd)

        if res.Err() != nil {
            log.Fatal(res.Err())
        }
    }

    return db.Collection(c)
}

好了,本文到此结束,带大家了解了《未经授权的错误可能会导致创建索引》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>