Adam Monsen
Adam Monsen

Reputation: 9420

How do I use my own data as the ID for a Doctrine MongoDB mapped document instead of the automatically generated Object ID?

The MongoDB documentation on Object IDs recommends using custom keys in a certain case:

If your document has a natural primary key that is immutable we recommend you use that in _id instead of the automatically generated ids.

How can I define a simple model object that does exactly this?

Upvotes: 3

Views: 1830

Answers (1)

Adam Monsen
Adam Monsen

Reputation: 9420

<?php

namespace Acme\HelloWorld\Model;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class KindWord {

  /**
   * @MongoDB\Id(strategy="NONE")
   * @var string
   */
  private $word;

  public function getWord() {
    return $this->word;
  }

  public function setWord($word) {
    $this->word = $word;
  }

}

Just make sure you set $word before calling persist().

Upvotes: 5

Related Questions