Php MongoWriteConcernException。(不可变)字段'_id';被发现已更改为_id
在CodeIgniter的MongoDB中进行更新时,我出现以下错误:Php MongoWriteConcernException。(不可变)字段'_id';被发现已更改为_id,php,mongodb,codeigniter,Php,Mongodb,Codeigniter,在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
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;
}
无法更新
\u id
字段
请注意,$userdata
对象变量包含\u id
字段,然后继续将该$userdata
对象作为要更新的值传递。因此,您正试图更新\u id
字段
执行'$set'=>$userdata时,需要从$userdata
中删除\u id
$collection->update(array('_id'=>new MongoId($id)),array('$set'=>$userdata),array('upsert'=>FALSE));
为什么错误消息解释不够?
\u id
字段是“不可变”的,这意味着您不能更改该值。如果您对数据库有一定的了解,那么“更改主键”应该是一个您理解的一般概念。即使值相同,您也必须从更新文档中删除_id字段,否则会发生此错误。对于答案,我确实犯了一个有趣的错误