FOSRestBundle and Mongodb cursor object to json

2019-09-17 18:30发布

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?

2条回答
Bombasti
2楼-- · 2019-09-17 18:46

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;
  }
查看更多
Ridiculous、
3楼-- · 2019-09-17 18:51

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.

查看更多
登录 后发表回答