I'm writing a little REST API with golang and mongodb official driver I'm stuck with error validation from mongodb.
Let me explain :
My Validation Schema (simplified)
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
}
So in my validation schema I required user lastname and give it a description to handle error with it (I understand that from documentation)
But with my create user func :
// 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
}
}
and my user struct
// User structure representation
type User struct {
ID primitive.ObjectID `bson:"_id"`
Lastname string `bson:"lastname"`
}
My json body from post http request
{
"something": "xxxx"
}
error expected: something like (exemple what I expected to have as error):
{
"field": "lastname",
"message": "must be a string and is required"
}
I got from my err :
multiple write errors: [{write errors: [{Document failed validation}]}, {<nil>}]
And from my err cast to WriteException:
Document failed validation
I read from documentation
description N/A string A string that describes the schema and has no effect.
But has no effect to validate or it's just as a comment for someone read schema?
I'd like to have my description about my error to display it to my http resp ! Maybe I'm in the wrong way to manage it so I'm ok to rewrite it !
Thank to read me and hope someone can help me with that :) Have a nice day