【发布时间】:2016-04-30 04:36:52
【问题描述】:
我希望你们能帮我解决这个问题:
首先要做的事情 - 我正在使用以下版本/库:
- PHP:PHP 7.0.3-1~dotdeb+8.1
- mongodb 版本 => 1.1.2
- Mongo PHPLibrary (https://github.com/mongodb/mongo-php-library/)
我正在尝试转换从数据库中取出的 BSON 数组,以便在我的项目中使用。
据我了解,MongoDB 的一大机遇是在一个集合中拥有不同的组织数据。 就像在这个例子中(其中只有一个对象有“描述”标签:
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
未定义“描述”标签的地方。
其实我希望它在不存在的地方返回 null。
我如何正确捕捉到某些数据集可能有也可能没有这个标签?
希望您能帮助我并感谢您的阅读:)
【问题讨论】:
标签: php mongodb exception bson