In my Symfony3 project, I do have some documents such as User, described below:
UserBundle\Document\User:
repositoryClass: UserBundle\Repository\UserRepository
fields:
userId:
id: true
email:
type: string
firstName:
type: string
lastName:
type: string
Some time, I want to create a user document through the user repository. Working around the createQueryBuilder(), I have built this method:
public function insert($email, $firstName, $lastName)
{
$data = array('email' => $email,
'firstName' => $firstName,
'lastName' => $lastName,
);
/* Create query */
$query = $this->createQueryBuilder();
/* Add Data */
$query
->insert()
->setNewObj($data);
/* Return */
$query
->getQuery()
->execute();
return true;
}
Rather than returning true
, I would like to return the Id of the document I have just created.
Looking for answers, I found this piece of code:
$this->getDocumentManager()->getConnection()->lastInsertId
Unfortunately, it is not returning what I am looking for:
object(MongoDB)[307]
public 'w' => int 1
public 'wtimeout' => int 10000
Thanks for your help !
EDIT:
Here is an updated code with the suggestion made in the accepted answer:
public function insert($email, $firstName, $lastName)
{
$id = new MongoId();
$data = array(
'_id' => $id,
'email' => $email,
'firstName' => $firstName,
'lastName' => $lastName,
);
/* Create query */
$query = $this->createQueryBuilder();
/* Add Data */
$query
->insert()
->setNewObj($data);
/* Return */
$query
->getQuery()
->execute();
return $id->__toString();
}