LearnBoost/mongoose — Issue #589: Unable to save object's data change when dynamically access object.
Author: murvinlai
Created: 2011-11-02 18:32:04+00:00
State: open

Here is the schema:

var StorageShema = new Schema(
sid: String,
vault: {},
date: Date
);
// then define the StorageModel....

Here is the original function:
addVault = function (sid, data, next) {
StarageModel.findOne(
{sid:sid}, function(err,doc) {
if (!err) {
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
doc.vault[prop] = data[prop]; // PROBLEM HERE
}
}

doc.save( function(err2) {
if (err2) {
next(err2);
} else {
next(null);
}
} );
}
}
);
};

----
What I 'm trying to do above is to dynamically assign different objects into Storage.vault .
It works when vault is empty. However, if something is in 'vault' already, any change to doc.vault will not be saved. and there is no error. Besides, I can see the new data in "doc.vault" before hitting save.

I have my solution,, which is first back up any object in doc.vault like this:
for (var prop in doc.vault) {
if (doc.vault.hasOwnProperty(prop)) {
temp[prop] = doc.vault[prop];
}
}

Then put new value into the temp object
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
temp.vault[prop] = data[prop];
}
}

then assign back to doc.vault

doc.vault = temp;

then hit doc.save and it will save.

I just don't know what I can't make change directly in doc.vault. Usually, if I change something like doc.sid or doc.date, and hit save, it will save the new change. Why it behaves differently with dynamic object and dynamic object referencing?