简体   繁体   中英

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

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; And 'Appliref' which contains an array

( ! It will not check if Appliref is an array only if it contains an array:

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

but my goal is, of course, to validate both, more specifically to check if Appliref is an array or not.

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

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,

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");
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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