简体   繁体   English

使用PHP在Mongodb上创建集合时对字段进行数组验证

[英]Array validation on a field at collection creation on Mongodb using PHP

I've got a little problem using MongoDB 3.2, PHP 5.6.16 with the PHPDriver mongod 1.1 and the 'official' MongoDB PHPLIB 使用MongoDB 3.2,PHP 5.6.16和PHPDriver mongod 1.1和“官方” MongoDB PHPLIB时,我遇到了一些问题

I want to create a collection with a validator: 我想使用验证器创建一个集合:

createCollection('client',[
'validator' => [
  'total' => ['$type' => 'int'],
  'Appliref' => ['$type'=> 'array'],
],
]);

If I do like presented, Mongo will check on insertion that my document contains 'total' which is an Int; 如果我喜欢演示,Mongo将在插入时检查我的文档是否包含“总计”(即Int); And 'Appliref' which contains an array 还有包含数组的“ Appliref”

( ! It will not check if Appliref is an array only if it contains an array: (!仅在包含数组的情况下,它不会检查Appliref是否为数组:

For example : 例如 :

insertOne([
  'total'=>55,
  'Appliref'=>array('1224','4447')]; will not be ok
insertOne([
  'total'=>55,
  'Appliref'=>array('1224',array('1111','2222'))]; will be ok )

The explanation is in the documentation of $type 说明在$ type的文档中

but my goal is, of course, to validate both, more specifically to check if Appliref is an array or not. 但我的目标当然是同时验证两者,更具体地说是检查Appliref是否为数组。

I found a solution on an other Website : 我在其他网站上找到了解决方案:

db.createCollection("user" , { validator : { "hoge.0" : {$exists : true}}})

the idea is to check if the first element of the array exists; 这个想法是检查数组的第一个元素是否存在;

I can't find a way to do it in PHP using the => and I not sure it's the perfect solution 我找不到使用=>在PHP中执行此操作的方法,但我不确定这是否是完美的解决方案

If someone got a solution ( for a PHP use please :( ) or a way to use the solution I found in PHP that would be great, 如果有人找到了解决方案(对于PHP使用,请::),或者使用我在PHP中发现的解决方案的一种方法,

Sorry for bad English, if there is. 对不起,英语不好,如果有的话。

Create an user define function with two parameters. 用两个参数创建一个用户定义函数。 One is for passing collection name and another one is for passing the array. 一个用于传递集合名称,另一个用于传递数组。 Now at the definition part of the function you can check the array as following code. 现在,在函数的定义部分,您可以按照以下代码检查数组。

function createMyCollection($collectionName,$array){
    if(is_array($array)){
       createCollection($collectionName,$array);
    }else{
       die("Invalid Array");
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM