Firebase实时数据库多路径更新失败

时间:2019-05-30 03:08:14

标签: node.js firebase-realtime-database google-cloud-functions

我正在尝试使用云功能(js sdk)在Firebase实时数据库上执行多路径更新。更新参数是通过forEach循环构造的。更新失败,并显示以下错误消息:
Error: Reference.update failed: First argument must be an object containing the children to replace.

考虑到console.log,我可能已经接近解决方案了:

[{"-LfzkTClUxC9J5y3Ue95/mood/sun":{"value":-75,"votecount":-1},"-LfzkTClUxC9J5y3Ue95/mood/rain":{"value":"7550","votecount":1}}, ... {"-LfzoAT7fPzhWsMpEU7t/mood/sun":{"value":0,"votecount":-1},"-LfzoAT7fPzhWsMpEU7t/mood/rain":{"value":"050","votecount":1}}]

这是我的云功能:

exports.updateGroupMood = functions.database.ref('users/{userId}/mood/')
.onUpdate((change, context) => {

const userId = context.params.userId //previous data
const beforeData = change.before.val()  //current data
const afterData = change.after.val()  
const userGroups = admin.database().ref('/users/' + userId +       
'/groups/social/Items'); //user groups to update

return userGroups.once("value")
.then(function(snapshot) {

var updateParams = []

snapshot.forEach(function(childSnapshot){

  const itemId = childSnapshot.key //id of group to update
  const moodRef = admin.database().ref('/groups/social/Items/' + itemId + '/mood/'); //node to update

  var promise = moodRef.once("value").then(function(snapshot) { //get values to update

    const objVal = snapshot.val()

    const previousMood = { // decrement previous values
      value:objVal[beforeData.element].value - beforeData.value,
      votecount:objVal[beforeData.element].votecount - 1,
    }
    const currentMood = { // increment new values
      value:objVal[afterData.element].value + afterData.value,
      votecount: objVal[afterData.element].votecount + 1,
    }  

    const newMood = { // update params definition
      [itemId + '/mood/' + beforeData.element]: previousMood,
      [itemId + '/mood/' + afterData.element]: currentMood,
    }
    return newMood

  });
  // construct update params
  updateParams.push(promise);

});
//get update params
return Promise.all(updateParams);
}).then(function(values) {

console.log(JSON.stringify(values)); //cf console.log in text above

const updateObj = admin.database().ref('/groups/social/Items/')

//update nodes
updateObj.update(JSON.stringify(values))   
})
})

1 个答案:

答案 0 :(得分:0)

您正在传递更新的JSON字符串,而实际上应该传递更新:

updateObj.update(values)