我在使用mongodb方面还很陌生。到目前为止,我真的很喜欢和mongogbb合作。但是,我很难使mongodb验证正常工作。在文档中,有一个很好的示例来实现上述验证。
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "gpa" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
gender: {
bsonType: "string",
description: "must be a string and is not required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
exclusiveMaximum: false,
description: "must be an integer in [ 2017, 3017 ] and is required"
},
major: {
enum: [ "Math", "English", "Computer Science", "History", null ],
description: "can only be one of the enum values and is required"
},
gpa: {
bsonType: [ "double" ],
minimum: 0,
description: "must be a double and is required"
}
}
}
}
})
上面提到的示例我尝试使用mongo-java-driver 3.3.0实现
public PlayerCrudManager(String collection) {
super(collection);
/** Create validation schema */
Bson forename = Filters.type("forename", BsonType.STRING);
Bson surname = Filters.type("surname", BsonType.STRING);
Bson email = Filters.regex("email", "@*.*$");
Bson password = Filters.type("passwordHash", BsonType.STRING);
Bson biography = Filters.type("biography", BsonType.STRING);
Bson nickname = Filters.type("nickname", BsonType.STRING);
Bson lokSafe = Filters.type("lokSafe", BsonType.BOOLEAN);
Bson captureQuickly = Filters.type("captureQuickly", BsonType.BOOLEAN);
Bson image = Filters.type("image", BsonType.STRING);
Bson timeStamp = Filters.type("timestamp", BsonType.TIMESTAMP);
Bson validator = Filters.and(forename, surname, email, password, biography, nickname, lokSafe, captureQuickly, image, timeStamp);
ValidationOptions validationOptions = new ValidationOptions().validator(validator);
super.getDb().createCollection(collection, new CreateCollectionOptions().validationOptions(validationOptions));
}
不幸的是,我想为每个属性实现描述,因为我希望能从mongo收到响应,指出哪个字段导致了失败。我理解这个描述标签对吗?使思路清晰。 我的主要目标是在mongo中插入任何json并在列出错误字段的地方获得响应。