简体   繁体   中英

How to update record array using cakephp and mongodb

I have a problem. I have this structure of db in mongodb:

id:"xxx",
is_validated: "xxx",
validation_code:"xxx",
profile:[
{
        profile_pic:"xxx",
    firstname:"xxx",
    lastname:"xxx",
}
]

I am using cakephp. When I update the record, I use this:

$this->User->set('id', "xxx");
$this->User->set('profile', array('firstname' => 'Benedict'));
$this->User->save()

When I save the record, the whole array of profile is deleted and only saves the "firstname":

id:"xxx",
is_validated: "xxx",
validation_code:"xxx",
profile:[
{
    firstname:"xxx"
}
]

I need to be able to save the firstname without deleting the other array records of mongodb using cakephp

Do you not follow the standard convention when using MongoDB? ( documentation ):

// where '1' is the id of your user    
$this->User->read(null, 1);
// set the new value for the field
$this->User->set('profile', array('firstname' => 'Benedict'));
// commit the changes to the database
$this->User->save();

Update

If the above doesn't work, try reading the whole record and modifying accordingly:

// set the active record
$this->User->id = 1;
// read the entire record
$user = $this->User->read();
// modify the field
$user['User']['profile']['firstname'] = 'Benedict';
// save the record
$this->User->save($user);

The reason this is happening is because you are asking for the profile field to be updated with the array that you pass. This then duly replaces the current profile array with yours.

To get round this you will have to pass the complete array in ie with the keys you want to keep and their values as well as the keys you want to change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM