MongoDB更新无法使用现有阵列

时间:2018-05-31 10:57:17

标签: php ajax mongodb symfony

对于解决这个问题的任何帮助,我将不胜感激。

我尝试使用PHP附加到MongoDB集合中的数组时没有成功。

过程如下:

用户选中一个复选框,然后点击相应的HTML“添加”按钮。 复选框的值是一个字符串,即'Manchester City Football Club - Conference And Events',字符串使用Ajax传递给Symfony控制器。

在Controller中检索字符串后,它将作为数组键存储在新的PHP数组中,并将“True”一词指定为键值。

如果当前系统用户以前没有尝试将数组保存到MongoDB集合中,那么MongoDB“insert”会成功创建一个新集合并将新创建的数组存储到集合中。

如果成功创建了MongoDB集合,则使用“更新”将新用户复选框选项添加到“marketingCategories”数组中。

这是Ajax脚本,它首先检索所选字符串并将其发送到Symfony控制器:

$('.addMPbtn').on('click', function(){
    var checkboxId = $(this).attr('checkboxId');
    if ($('#'+checkboxId).is(":checked"))
    {
      var checkboxVal = $('#'+checkboxId).val();
      // console.log(checkboxVal);

      // Fire off the request to the controller 
        request = $.ajax({
            url: "{{ path('sendManagedPreferences') }}",
            type: "POST",
            data: {"mpString" : checkboxVal},
        });

        // Callback handler that will be called on success
        request.done(function (response){
            console.log(response);
        });
    }
})

以下是PHP(Symfony Controller)脚本,用于与MongoDB集合进行交互:

class sendManagedPreferencesController extends Controller
{

    public function indexAction(){

        /** @var $user \Attain\Dashboard\Document\User */
        $user = $this->get('security.context')->getToken()->getUser();
        $domainName = $user->getDomain();
        $userId = $user->getId();

        $mpDataArray = array();

        // Get the request method.
        $request = $this->get('request');

        if ($request->getMethod() == 'POST') {

            $mpString = $request->get('mpString');

            $mpDataArray[$mpString] = "true";

            // Connection details omitted
            $usersCollection = $mongoDB->selectCollection($domainName.'_managedPreferences');

            // Search criteria for use within a mongodb query
            $querySettings = array('userId' => array('$exists' => true));

            $cursorSettings = $usersCollection->findOne($querySettings);

            if(!isset($cursorSettings['userId'])) {

                // If their is no data stored within the domain_managedPreferences collection relating to the current user then
                // prepare a suitable array which can be used to insert into the collection.

                $newUserMC = array('userId' => $userId,'marketingCategories' => $mpDataArray);

                $usersCollection->insert($newUserMC);

            } else {

                $documentId = $cursorSettings['_id']->{'$id'};

                $existingUserMC = array('marketingCategories' => $mpDataArray);

                // If the current user has data stored within the domain_managedPreferences collection then we prepare an array
                // which can be used to append any selected marketing categories to the existing collection.

                if($documentId !='') {

                    $usersCollection->update(
                        array( '_id' =>  new \MongoId($documentId) ),
                        array( '$addToSet' => $existingUserMC )
                    );

                }

            }

        unset($mpDataArray);

        echo "Ajax procedure was successful.";

        }
    }
}

以下是新创建的MongoDB集合的结构:

{
   "_id": ObjectId("5b0e98e899eccf502400003e"),
   "userId": "5ab8fb0f0efafb444e800e1e",
   "marketingCategories": {
     "Manchester City Football Club - Conference And Events": "true" 
  } 
}

0 个答案:

没有答案