mongoDB wont allow me to update

691 views Asked by At

Ok this issue is driving me nutts, I thought that _id was meant to be ObjectID while the first time it inserts it does it correctly when I try to update it using the _id it does not work.

here is my code

//Save Data
    function savedata($data){
        $collection = $this->db->retail_logs;
        $this->data = $data;

        if($this->data['_id'] == NULL || $this->data['_id'] == "")
        {
            $this->data['_id'] = new MongoId();
        }
        else
        {
         $this->data['_id'] = ObjectID($this->data['_id']);
        }   
        try {
        $collection->update(
            array("_id"=>$this->data['_id']),
            $this->data, // new lead document to insert
            array("upsert" => true, "safe" => true)
            );

            print $this->data['_id'];
        } catch (Exception $e) {
            print "we are not able to update";
        }
    }

i have tried to do the followinf

if($this->data['_id'] == NULL || $this->data['_id'] == "")
            {
                $this->data['_id'] = new MongoId();
            }
            else
            {
             $this->data['_id'] = ObjectID($this->data['_id']);
            }   

but that seems not to help.

What Is happening is it inserts the first time correctly with ObjectID(idnumber) then when it goes to update is removes the ObjectID() and inserts a new lead with the same idnumber as before

so it looks like "IDNUMBER"

2

There are 2 answers

0
Stennie On BEST ANSWER

Your original code is close, but if you want to make a string _id the correct ObjectID type, use:

$this->data['_id'] = new MongoId($this->data['_id']);
0
user1071979 On

Checking the Outcome of an Update Request

A non-upsert update may or may not modify an existing object. An upsert will either modify an existing object or insert a new object. The client may determine if its most recent message on a connection updated an existing object by subsequently issuing a getlasterror command ( db.runCommand( "getlasterror" ) ). If the result of the getlasterror command contains an updatedExisting field, the last message on the connection was an update request. If the updatedExisting field's value is true, that update request caused an existing object to be updated; if updatedExisting is false, no existing object was updated. An "upserted" field will contain the new _id value if an insert is performed (new as of 1.5.4)

Can you run the command as suggested by Mongo Docs and let us know the result of the command

Reference: Mongo Updating