我的問題是,當我提交表單並將其記錄到MongoDB。更新的PHP MongoDB未設置字段
我能夠使用更新將新字段添加到文檔,我可以更改它們的值和鍵,但我無法刪除/取消設置它們。
我對Mongo很新。我通常使用堆棧:MySQL + PHP + Bootstrap,但出於生產原因,我們需要將Mongo添加到方程中。
下面是我收集的文檔外觀:
{
"_id": ObjectId("58a44a61e09075e805d63af1"),
"en": "Cat",
"de": "Katze",
"es": "Gato",
}
期間提交,我可以編輯這樣說:
{
"_id": ObjectId("58a44a61e09075e805d63af1"),
"en": "Cat",
"de": "Katze",
"fr": "Chat",
}
或者這樣說:
{
"_id": ObjectId("58a44a61e09075e805d63af1"),
"en": "Cat",
"de": "Katze",
"es": "Gato",
"fr": "Chat",
}
但我無法這樣做:
{
"_id": ObjectId("58a44a61e09075e805d63af1"),
"en": "Cat",
"de": "Katze"
}
這裏是我的形式:
<form role="form" action="" method="post">
<table>
<?php
foreach ($glossary as $term) {
foreach (array_slice($keys,1) as $key => $value) {
echo "<tr id='language" . $key . "' class='languages'>";
echo "<td>";
echo "<select class='form-control' name='lang" . $key . "'>";
echo "<option value='' selected></option>";
// Options not shown for simplicity.
echo "</select>";
echo "</td>";
echo "<td>";
echo "<input class='form-control' value='$term[$value]' name='langInput" . $key . "'>";
echo "</td>";
echo "</tr>";
}
}
}
?>
</table>
<input type="submit" name="submit" class="btn btn-primary" value="Save Changes">
在提交時我做的:
$termArray = array();
// Get submitted form vars
for ($i = 0; $i <= $loop; $i++) {
$langCode = cleanFormFld($_POST["lang".$i]);
$termArray[$langCode] = cleanFormFld($_POST["langInput".$i]);
}
try {
$connection = new Mongo("mongodb://$dbhost");
$db = $connection->$dbname;
$db->terms->update(array('_id' => new MongoId($id)), array('$set' => $termArray));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
每langX和langInputX在jQuery的dinamicaly創建。
也許我很困惑,但你需要['$ pull'(https://開頭docs.mongodb.com/manual/reference/operator/update/pull/)而不是'$ set'來刪除數組元素 –
感謝hd,但我只是使用了$ pull,但沒有發生任何事情。 – anexo