0

I'm currently working on a RESTful API using Symfony2 with FOSRestBundle.

I love Mongodb, so i've implemented just that, here is a snippet of my usercontroller.

  /**
   * @return View view instance
   * @View()
   */
  public function allAction() {
    $users = $this->get('doctrine_mongodb')
      ->getRepository('FantasytdUserBundle:User')
      ->findByUsername('Elvar');

    return $users;
  }

So i am finding a User in the Database, which yields a result. Were this done with mysql database this snippet would work. But with mongodb, the get method returns a Cursor object, and when this is returned, you get something like this.

[{"message":"[Semantical Error] Annotation @Secure is not allowed to be declared on class JMS\\SecurityExtraBundle\\Annotation\\Secure. You may only use this annotation on these code elements: METHOD.","class":"Doctrine\\Common\\Annotations\\AnnotationException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":"\/Users\/Elvar\/Projects\/fantasytd\/backend\/vendor\/doctrine\/common\/lib\/Doctrine\/Common\/Annotations\/AnnotationException.php","line":52,"args":[]},

And it goes on.

How should i approach these cursor objects?

MartinElvar
  • 5,695
  • 6
  • 39
  • 56
  • The error that you get is thrown in Symfony 2.1 if you try to secure a whole controller using the `Secure(roles="ROLE_ADMIN")` annotation. Use `@PreAuthorize("hasRole('ROLE_ADMIN')")` instead (see: http://stackoverflow.com/a/12001097/601386). – flu Jan 07 '13 at 17:42
  • If you use @PreAuthorize don't forget to add `expressions: true` to your configuration under `jms_security_extra:`. It defaults to `false`. – flu Jan 08 '13 at 13:14

2 Answers2

2

Apparently it works if the result yields only one result, so using FindOneByUsername() solves the problem.

If you need multiple result, i solved it by looping though.

 public function allAction() {
    $usersQ = $this->get('doctrine_mongodb')
      ->getRepository('FantasytdUserBundle:User')
      ->findByUsername('Elvar');

    foreach ($usersQ as $user) {
      $users[] = $user;
    }

    return $users;
  }
MartinElvar
  • 5,695
  • 6
  • 39
  • 56
1

Instead of running through the list with a foreach loop, we're using "->toArray()" on the Cursor object - it's just a little simpler. I believe iterator_to_array() should do the trick as well.