如何正确地将 MongoDB BSON 转换为 PHP 对象

How to properly convert MongoDB BSON into PHP Object

我希望你们能帮助我:

首先要做的事情 - 我正在使用以下版本/库:

我正在尝试转换我从数据库中获取的 BSON 数组,以便在我的项目中使用。

据我了解,MongoDB 的一大机遇是在一个集合中拥有不同组织的数据。 就像在这个例子中一样(只有一个对象有 "description" 标签:

JSON 文件:

{
    enumbers ":[ {
        "id": "84",
        "enumber": "E 472 b",
        "name": "Milchs\u00e4ureester von Mono- und Diglyceriden von Speisefetts\u00e4uren"
    }, {
        "id": "198",
        "enumber": "E 407",
        "name": "Carrageen",
        "description": "Testdescription",
    }, {
        "id": "293",
        "enumber": "E 941",
        "name": "Stickstoff"
    }]
}

我正在使用以下代码访问数据库:

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "test", "items");
$document = $collection->findOne(["id" => '5']);
$product= new Product($document);

到这里为止一切正常。

use MongoDB\Model\BSONArray;
use MongoDB\Model\BSONDocument;
class Product
public function __construct(BSONDocument $data)
{


    foreach ($data as $part){
        try{
        $this->setId($part->id);
        $this->setEnumber($part->id);
        $this->setName($part->name);
        --------------------------------------
        $this->setDescription($part->description);
        --------------------------------------
        }catch (\Exception $e){
            echo $e;
        }

    }

    echo "-------------------------------------------------".PHP_EOL;

}

现在“$this->setDescription($part->description);”抛出异常:

ErrorException: Trying to get property of non-object

未定义 "description" 标记。

实际上我希望它在不存在的地方返回 null。

我如何正确地捕捉到一些数据集可能有也可能没有这个标签?

希望你能帮助我并感谢阅读:)

我发现我试图在我的函数中访问一层 "too deep"。 当我尝试访问

$this->setDescription($data->description);

我可以检查它是否已设置:

if (isset($data->name)) $this->setName($data->name);

有效。

我以为我已经尝试过但没有结果 - 但我认为写一篇适当的论文会导致过度阅读这个。