【发布时间】: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