Fatmuemoo
Fatmuemoo

Reputation: 2217

doctrine 2 ODM preventing duplicate record

Doctrine NOOB here, trying to figure out how to prevent a duplicate record in an embed many property. I have a EmbededDocment like this:

<?
/**
 * @EmbeddedDocument
 */
class Contact {
/**
 * @Id
 */
private $id;

/**
 * created timestamp
 * @Date
 */
private $created;

/**
 * modified timestamp
 * @Date
 */
private $modified;

/**
 * @String
 */
private $name;

 /**
 * @String
 */
private $name;

 /**
 * @String
 */
private $address;
 }

what I want to happen is when I add a new contact, two contacts can have the same name, two contacts can have the same address, but two contacts can not have the same name and address. When checking for duplicates, doctrine will need to ignore the $id, $created and $modified properties as these will almost always be distinct. It is the combination of all the other fields that must be unique. How can this be accomplished using doctrine? Does this logic belong in a service layer or can doctrine do it for me?

UPDATE: I do accept that Andrew's answer is the correct way to check for duplication using Mongo, I really want to know if doctrine can do this for me. Therefore, I'm starting a bounty.

Upvotes: 6

Views: 1868

Answers (2)

Reuven
Reuven

Reputation: 3336

You could implement an event listener which will listen to an preUpdate and prePersist event. http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/events.html

In your event, you can do your own check.

Upvotes: 1

Andrew Orsich
Andrew Orsich

Reputation: 53685

You should validate your document before save it.

For example if user adding Contact with name="Name" and address="Address" you shoud check in mongodb if such Contact exists. And in case if it exists you just showing validation message, otherwise you adding contact to embedded contacts array.

So, suppose you have collection of users that's contains embedded array of contacts. To verify that new contact exists/not exists you can send request like this:

db.users.find({ userId: "userId" , 
                contacts.name: "new contact name", 
                contacts.address: "new contact address"}).count();

If above query will return count >= 1 you no need add new contact, just show validation.

Upvotes: 1

Related Questions