2

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

3 Answers 3

1

Currently (MongoDB v4.4) the reason for document validation failure is not returned back by the MongoDB server. There is an open issue SERVER-20547 to track this work. Please feel free to watch or up-vote the ticket to receive progress update.

You should implement an application level input validation. Ensuring that the inputs are in the correct data types before database insertion.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes thank you, I did a struct validation before insert to db. I'll follow this issue
1

You can use this tool to create schemas from you golang structs https://github.com/s-augustovitko/mongo-schema-go

Comments

0

You need to declare the id field in the properties because the additionalProperties attribute was set to false. Mongodb automatically injects the _id field into the document that will be inserted into the collection, for data processing performance.

Below is the example of the scheme you are using added to the _id property:

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",
        },
    },
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.