用于 mongodb 的 JsonSchema 看起来像这样:
package main
import (
"context"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
jsonSchema := bson.M{
"bsonType": "object",
"required": []string{"name", "age"},
"properties": bson.M{
"name": bson.M{
"bsonType": "string",
"minLength": 1, // Minimum length of 1 character
"maxLength": 50, // Maximum length of 50 characters
"description": "must be a string with 1 to 50 characters and is required",
},
"age": bson.M{
"bsonType": "int",
"minimum": 0,
"description": "must be an integer greater than or equal to 0 and is required",
},
},
}
validationOptions := options.CreateCollection().SetValidator(bson.M{"$jsonSchema": jsonSchema})
err = db.CreateCollection(context.TODO(), "your_collection_name", validationOptions)
collection := db.Collection("your_collection_name")
newPerson := Person{Name: "John Doe", Age: 30} // NUM #1
insertResult, err := collection.InsertOne(context.Background(), newPerson)
// or we could do this instead:
newPerson := bson.D{{"name", "John Doe"}, {"age", 30}} // NUM #2
insertResult, err := collection.InsertOne(context.Background(), newPerson)
}
我的问题是 - 是否有一个库/技术可以在插入该数据库之前根据 jsonSchema 映射定义验证 person 结构(#1)或 bson.M person 映射(#2)?这样我们就可以在应用程序级别尽早失败,并知道 struct/bson.M 声明与模式匹配。 (并在应用程序层进行测试)。
这似乎可行,但如果有人知道更好的方法,请告诉我:
import (
"encoding/json"
"github.com/xeipuuv/gojsonschema"
)
func validateAgainstSchema(doc bson.M, jsonSchema string) error {
jsonDoc, err := json.Marshal(doc)
if err != nil {
return err
}
documentLoader := gojsonschema.NewStringLoader(string(jsonDoc))
schemaLoader := gojsonschema.NewStringLoader(jsonSchema)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return err
}
if !result.Valid() {
return errors.New(result.String())
}
return nil
}
bsonDoc := bson.M{"name": "John", "age": 30}
err := validateAgainstSchema(bsonDoc, yourJSONSchemaString)
if err != nil {
// Handle validation error
}