0

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I tried your method, it still removed the other fields in my profile array. :(
Hi sam, thanks for your quick response. I tried your code, cake is still not saving the record. I placed the save function in an "if" statement and echoed a text to check and it is saving, but the change is not reflected on the database.
Hi Sam, thanks for your answer. It did save the correct file when i tweaked something on your code. Thanks a lot!
No worries @comebal, would you mind editing my code please so that it works for others too, Thank you!
0

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 i.e. with the keys you want to keep and their values as well as the keys you want to change.

1 Comment

then that'll mean that I have to query the other records in "profile"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.