2015-09-08 60 views
4

雖然笨作出更新MongoDB中,我有以下錯誤:MongoWriteConcernException。的(immutable)的字段「_id」被發現被改變爲_id

Type: MongoWriteConcernException 

Message: localhost:27017: After applying the update to the document {_id: ObjectId('55ee98543bd7af780b000029') , ...}, the (immutable) field '_id' was found to have been altered to _id: "55ee98543bd7af780b000029" 

Filename: C:\xampp\htdocs\CI\application\models\mongo_model.php 

這裏是我的控制器代碼

public function update() 
{ 
    $userdata['firstname'] = $this->input->post('txtfirstname'); 
    $userdata['lastname'] = $this->input->post('txtlastname'); 
    $userdata['email'] = $this->input->post('txtemail'); 
    $userdata['password'] = md5($this->input->post('txtpassword')); 
    $userdata['_id'] = $this->input->post('hiddenId'); 
    $collection= $this->mongo_model->updateuserdb($userdata); 
    if ($collection) 
    { 
     header('location:'.base_url()."index.php/user".$this->index()); 
    } 
} 

和模型代碼是

public function updateuserdb($userdata) 
{ 
    $id = $userdata['_id']; 
    $collection = $this->mongo_db->db->selectCollection('myfirstCollection'); 
    $query = $collection->update(array('_id' => new MongoId($id)), array('$set' => $userdata), array('upsert' => FALSE)); 
    return $query; 
} 
+0

錯誤信息如何解釋不夠? '_id'字段是「不可變的」,這意味着你不能改變它的值。如果你對數據庫有一般的瞭解,那麼「修改主鍵」應該是你理解不了的一般概念。 –

+1

即使值相同,您也必須從更新文檔中移除_id字段,否則會發生此錯誤 – Sammaye

回答

3

您不能更新_id領域。

請注意,您的$userdata對象變量包含_id字段,然後您繼續傳遞該對象作爲要更新的值。因此,您正試圖更新_id字段。

您需要從$userdata刪除_id當做' $ set'=> $ userdata

$collection->update(array('_id'=>new MongoId($id)),array('$set'=>$userdata),array('upsert'=>FALSE)); 
+0

感謝您的答案我真的犯了這個有趣的錯誤 –