MongoWriteConcernException.发现(不可变)字段'_id'已被更改为_id

Ume*_*rse 8 php codeigniter mongodb

在CodeIgniter中使用MongoDB进行更新时出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

这是我的控制器代码

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

和型号代码是

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;
}
Run Code Online (Sandbox Code Playgroud)

why*_*ite 7

您无法更新该_id字段.

请注意,您的$userdata对象变量包含该_id字段,然后您继续将该$userdata对象作为要更新的值传递.因此,您正在尝试更新该_id字段.

在执行'$ set'=> $ userdata时,您需要删除_idfrom .$userdata

$collection->update(array('_id'=>new MongoId($id)),array('$set'=>$userdata),array('upsert'=>FALSE));
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回答我真的犯了那个有趣的错误 (2认同)