The problem
Empty objects in Mongo are decoded to empty array in PHP. It leads to a problem that after I do json_encode($data)
the values which supposed to be {}
in json are encoded to []
.
Configuration
Image you have a document mapped to Mongo like that:
/**
* @MongoDBEmbeddedDocument()
*/
class RandomForm
{
/**
* @var mixed
* @MongoDBField(type="raw")
*/
private $content;
}
Why? Frontend draws "random" forms (it knows how forms should look like from other sources) and wants to save the data. To do it the frontend simply sends JSON to backend. And when frontend asks for data it wants to get it back. For what ever reason we would like to search by that random fields in our database.
It works pretty good unless frontend sends us empty object, which is stored to Mongo as empty Object
, but PHP does its magic and converts it to empty Array
.
Is there any way to keep the original data type (object or array) from Mongo?
Limitations
You can't just convert all empty arrays to objects (stdClass()
) because sometimes it should still be empty array.
Mongo guys says they are not going to fix it in driver: https://jira.mongodb.org/browse/PHP-550
Is there any way to bypass this behavior?
question from:
https://stackoverflow.com/questions/65902607/retrieve-empty-objects-without-having-an-empty-array-from-mongodb-with-php 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…