MongoLab:使用PHP使用CURL进行PUT更新

sam*_*ski 1 php curl mongodb mlab

我一直在尝试使用MongoLabs api来简化我的生活,并且在大多数情况下它一直在工作,直到我尝试使用php和curl将更新推送到数据库,无论如何都没有骰子.我的代码与此类似:

$data_string = json_encode('{"user.userEmail": "USER_EMAIL", "user.pass":"USER_PASS"}');
try { 
$ch = curl_init();

//need to create temp file to pass to curl to use PUT
$tempFile = fopen('php://temp/maxmemory:256000', 'w');
if (!$tempFile) {
    die('could not open temp memory data');
}
fwrite($tempFile, $data_string);
fseek($tempFile, 0); 

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
//curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
//curl_setopt($ch, CURLOPT_INFILE, $tempFile); // file pointer

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, DB_API_REQUEST_TIMEOUT);                                                                    
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                     
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                       
    'Content-Length: ' . strlen($data_string),
    )                                                                              
);   

$cache = curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {
    return FALSE;
}
Run Code Online (Sandbox Code Playgroud)

我的问题似乎与MongoLab的api有关.代码位完美无缺,除了实验室告诉我我传递的数据是'无效对象{"user.firstName":"Pablo","user.newsletter":"true"}:存储在db不能拥有.在他们中.'.我试过传递一个文件并使用postfields,但都没有奏效.

当我在firefox的Poster插件上测试它时,该值工作正常.如果有人对MongoLabs的东西有了更好的了解,我会喜欢一些启示.提前致谢!

jar*_*red 6

您需要从字段名称中删除点.您可以尝试使用以下模式:

{ "user": { "userEmail": "USER_EMAIL", "pass": "USER_PASS" } }
Run Code Online (Sandbox Code Playgroud)

不幸的是,MongoDB不支持在字段名称中使用点.这是因为它的查询语言使用点作为运算符来链接嵌套的字段名称.如果MongoDB允许在字段名称中使用点,则在没有某种转义机制的情况下,查询将变得模糊不清.

如果此文件合法:

{ "bow.ties": "uncool", "bow": { "ties": "cool" } }
Run Code Online (Sandbox Code Playgroud)

这个查询不明确:

{ "bow.ties": "cool" }
Run Code Online (Sandbox Code Playgroud)

不清楚文件是否匹配.你的意思是"bow.ties"字段或字段"tie"嵌套在字段"bow"的值内吗?

这是一个mongo shell会话的捕获,展示了这些想法.

% mongo
MongoDB shell version: 2.1.1
connecting to: test
> db.stuff.save({"bow.ties":"uncool"})
Wed Jul 18 11:17:59 uncaught exception: can't have . in field names [bow.ties]
> db.stuff.save({"bow":{"ties":"cool"}})
> db.stuff.find({"bow.ties":"cool"})
{ "_id" : ObjectId("5006ff3f1348197bacb458f7"), "bow" : { "ties" : "cool" } }
Run Code Online (Sandbox Code Playgroud)