更新嵌套对象Firebase [英] Updating nested objects firebase
问题描述
从Firebase注意:
From the Firebase note:
给出像 alanisawesome
, updateChildren()
之类的单个键路径仅更新第一个子级别的数据,并且处理传递到第一个子级别之外的任何数据作为 setValue()
操作.多路径行为允许使用更长的路径(例如 alanisawesome/nickname
)而不会覆盖数据.这就是第一个示例与第二个示例不同的原因.
Given a single key path like alanisawesome
, updateChildren()
only updates data at the first child level, and any data passed in beyond the first child level is a treated as a setValue()
operation. Multi-path behavior allows longer paths (like alanisawesome/nickname
) to be used without overwriting data. This is why the first example differs from the second example.
我正在尝试在代码中使用单个函数 createOrUpdateData(object)
.如果进行更新,它将正确更新第一级子级,但是如果我已传递嵌套对象,则它将删除该嵌套对象的所有其他属性.
I am trying to use a single function createOrUpdateData(object)
in my code. In case of update, it updates first level children properly, but if I have nested object passed, then it deletes all other properties of that nested object.
这是代码:
function saveUserDetails(email,object){
var hashedEmail = Utilities.getHashCode(email);
var userRef = ref.child(hashedEmail);
return $q(function(resolve,reject){
return userRef.update(object, function(error){
if(error){
reject(error);
}else{
resolve("Updated successfully!");
}
});
});
}
所以,如果我通过:
{
name: 'Rohan Dalvi',
externalLinks: {
website: 'mywebsite'
}
}
然后它将删除externalLinks对象内的其他属性.有没有更干净,更简单的方法来避免这种情况?
Then it will delete other properties inside externalLinks object. Is there a cleaner and simpler way of avoiding this?
简而言之,如何确保仅更新嵌套对象而不会删除数据.
In short, how do I make sure nested objects are only updated and that data is not deleted.
推荐答案
您可以使用多路径更新.
var userRef = ref.child(hashedEmail);
var updateObject = {
name: 'Rohan Dalvi',
"externalLinks/website": 'mywebsite'
};
userRef.update(updateObject);
通过在对象文字中使用"externalLinks/website"
语法,它将嵌套路径视为更新,而不是嵌套对象的集合.这可防止嵌套数据被删除.
By using the "externalLinks/website"
syntax in the object literal it will treat the nested path as an update and not a set for the nested object. This keeps nested data from being deleted.
这篇关于更新嵌套对象Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!