【问题标题】:Golang mongodb driver error schema validationGolang mongodb驱动错误模式验证
【发布时间】:2020-12-20 10:13:39
【问题描述】:

我正在使用 golang 和 mongodb official driver 编写一个小的 REST API 我被 mongodb 的错误验证困住了。

让我解释一下:

我的验证架构(简化)

var jsonSchema = bson.M{
    "bsonType":             "object",
    "required":             []string{"lastname"},
    "additionalProperties": false,
    "properties": bson.M{
        "lastname": bson.M{
            "bsonType":    "string",
            "description": "must be a string and is required",
        },
    },
}

var validator = bson.M{
    "$jsonSchema": jsonSchema,
}

// Migrate create users collection with validation schema
func (r *Repo) Migrate() error {

    opts := options.CreateCollection().SetValidator(validator)

    if err := r.db.CreateCollection(r.ctx, "users", opts); err != nil {
        return err
    }

    return nil
}

所以在我的验证模式中,我需要用户姓氏并给它一个描述以处理错误(我从文档中了解到)

但是使用我的创建用户功能:

// Create user to repo
func (r *Repo) Create(usr *User) {
    if r.err != nil {
        return
    }
    u := r.db.Collection("users")
    _, err := u.InsertOne(r.ctx, usr)
    if err != nil {
        we, ok := err.(mongo.WriteException)
        if ok {
            fmt.Println(we)

            for _, r := range we.WriteErrors {
                fmt.Println(r)
            }

        }
        r.err = fmt.Errorf("error occured during creating. got=%w", err)
        return
    }
}

和我的用户结构

// User structure representation
type User struct {
    ID        primitive.ObjectID `bson:"_id"`
    Lastname  string             `bson:"lastname"`
}

来自 post http 请求的我的 json 正文

{
  "something": "xxxx"
}

预期错误: 类似的东西(例如我期望的错误):

{
    "field": "lastname",
    "message": "must be a string and is required"
}

我从我的错误中得到: multiple write errors: [{write errors: [{Document failed validation}]}, {<nil>}]

从我的错误转换为 WriteException: Document failed validation

我读过from documentation description N/A string A string that describes the schema and has no effect. 但是对验证没有影响,或者它只是作为对某人阅读架构的评论?

我想对我的错误进行描述,以将其显示到我的 http resp ! 也许我的管理方式不对,所以我可以重写它!

感谢阅读我并希望有人可以帮助我:) 祝你有美好的一天

【问题讨论】:

    标签: mongodb validation go


    【解决方案1】:

    目前(MongoDB v4.4)MongoDB 服务器不返回文档验证失败的原因。有一个未解决的问题SERVER-20547 来跟踪这项工作。请随时观看或投票以接收进度更新。

    您应该实现应用程序级别的输入验证。在插入数据库之前确保输入的数据类型正确。

    【讨论】:

    • 是的,谢谢,我在插入数据库之前进行了结构验证。我会关注这个问题
    【解决方案2】:

    您需要在属性中声明 id 字段,因为 additionalProperties 属性设置为 false。 Mongodb 会自动将 _id 字段注入到将被插入到集合中的文档中,以提高数据处理性能。

    下面是您正在使用的添加到 _id 属性的方案示例:

    var jsonSchema = bson.M{
        "bsonType":             "object",
        "required":             []string{"lastname"},
        "additionalProperties": false,
        "properties": bson.M{
            "_id": bson.M{
                "bsonType": "objectId",
            },
            "lastname": bson.M{
                "bsonType":    "string",
                "description": "must be a string and is required",
            },
        },
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 2020-02-02
      • 1970-01-01
      • 2017-04-09
      • 2018-07-10
      • 2019-01-26
      • 2016-10-05
      • 1970-01-01
      • 2018-10-22
      相关资源
      最近更新 更多