【发布时间】:2018-07-16 20:28:25
【问题描述】:
我正在尝试通过 Java 在 MongoDB(3.4) 中创建一个带有验证的集合。
在 shell 中执行时可以正常工作:
db.createCollection( "accounts",
{
validator: { $and:
[
{ username: { $type: "string" } },
{ email: { $regex: /@*\.*$/ } },
{ password: { $type: "string" } }
]
}
}
)
所以现在我想用 java 中的验证创建相同的集合。可悲的是,我在这里找到的先前答案正在使用已弃用的方法。
这是我尝试过的,因为验证器字段是一个选项字段。
//String createDatabase = "{ 'validator': { '$and':[{ 'username': { '$type': 'string' } },{ 'email': { '$regex': '@*.*$' } },{ 'password': { '$type': 'string' } }]}}";
String createDatabase = " { \"validator\": { \"$and\":[{ \"username\": { \"$type\": \"string\" } },{ \"email\": { \"$regex\": \"@*.*$\" } },{ \"password\": { \"$type\": \"string\" } }]}}";
JsonParser jsonParser = new JsonParser();
DBObject dbobj= (DBObject) JSON.parse(createDatabase);
getMongoClient().getDatabase(DATABASE_NAME).createCollection(collectionName, new CreateCollectionOptions().validationOptions(new ValidationOptions().validator((Bson) dbobj)) );
这是我得到的例外。我认为这是因为无法解析 json,我检查了它是否有效并且应该是。
{
"validator": { "$and":
[
{ "username": { "$type": "string" } },
{ "email": { "$regex": "@*.*$" } },
{ "password": { "$type": "string" } }
]
}
}
上面是我试图解析的 json。
com.mongodb.MongoCommandException: Command failed with error 2: 'unknown operator: $and' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "unknown operator: $and", "code" : 2, "codeName" : "BadValue" }
【问题讨论】:
标签: java json mongodb validation mongodb-query