We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to validate unique field in mongodb

Hello. How i can validate mongodb collection by Uniqueness? I get error

Call to undefined method ::getschema()

my code is

use Phalcon\Mvc\Model\Validator\Uniqueness;
use Phalcon\Mvc\Model\Validator\PresenceOf;
use Phalcon\Mvc\MongoCollection;

class Users extends MongoCollection {

    public $name;
    public $password;

    public function validation() {
        $this->validate(new PresenceOf([
            "field" => "name",
            "message" => "The name is required",
        ]));
        $this->validate(new PresenceOf([
            "field" => "password",
            "message" => "The pasword is required",
        ]));
        $this->validate(new Uniqueness([
            "field" => "name",
            "message" => "Name must be unique",
        ]));

        return $this->validationHasFailed() !== true;
    }

}


43.9k

Hi,

in API doc, there is no Phalcon\Mvc\MongoCollection . I think, you have to use Phalcon\Mvc\Collection instead. https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Collection.html#abstract-class-phalcon-mvc-collection

There is no way. From Phalcon 3.1(currently alpha) there will be a way to use Collection and Uniqueness validator. Also there will be added support for Collections to use Phalcon\Validation and it should be used and Phalcon\Mvc\Model\Validator will be deprecated.