2017-08-07 26 views
1

因此,我試圖實現的是更新user.profile,以保留user.profile中已存在的舊未更新數據。用流星中的動態對象更新user.profile

所以,我最初的user.profile有以下幾點:

{ 
    accountType: 'Student', 
    xyz: 'something', 
    etc... 
} 

在我更新的方法,我想繼續,如果不需要更新這些值,所以如果我想添加以下內容:

{ 
    'xyz': 'something else', 
    'bar': 'bar', 
    etc... 
} 

我希望看到兩個對象合併和更新後的更新配置文件。

我試圖用是updateupsert,但在這兩種情況下,我的所有的測試,當我嘗試更新user.profile舊數據得到完全被新的數據替換...

這裏是我的一個最新的嘗試:

Meteor.users.update(this.userId, { 
    $set: { 
    profile: data 
    } 
}, 
{ upsert: true }); 

,但我也試過:

Meteor.users.upsert(this.userId, { 
    $set: { 
    profile: data 
    } 
}); 

我如何能實現我需要什麼?由於

回答

2

Mongo documentation

的$集合運算符代替了場與指定的值。

因此,當您將其更新爲{ $set: { profile: ... } }時,它將替換整個profile文檔。

你應該使用這樣的:

$set: { 
    'profile.<field_name>': '<field_value>', 
    ... 
} 

下面是代碼做你的情況:

const $set = {}; 
_.each(data, (value, key) => { 
    $set[`profile.${key}`] = value; 
}); 
Meteor.users.update(this.userId, { $set }); 
+0

真棒,我非常喜歡這個方案。它充當魅力!乾杯! –