Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

Retrieve empty objects without having an empty array from MongoDB with PHP

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...