当使用.push方法时,我可以写一个id的副本给对象? [英] When utilizing the .push method can I write a copy of the id to the object?

查看:307
本文介绍了当使用.push方法时,我可以写一个id的副本给对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在firebase上使用.push方法来写入新记录。我想保存新记录的关键点保存到记录本身的ID键。目前,我在2个操作中执行此操作,首先推送记录,然后使用返回的ref进行更新。我可以在1写吗?这没有关系吗?

I'm using the .push method on firebase to write new records. I'd like to save the key where the new record is saved to the record itself at the id key. Currently, I do this in 2 operations, first push the record and then update using the ref returned. Can I do this in 1 write? Does it not matter?

推荐答案

在一个操作中没有办法做到这一点。但是,通常无关紧要,因为您始终可以从 .key()方法获取 DataSnapshot

There's no method to do this in one operation. However, it typically does not matter, because you can always get the push id from the .key() method on the DataSnapshot.

但是,存储推送ID也没有错。因此,您可以在 Firebase 原型上创建一个函数。

But, there's nothing wrong either about storing the push id. So you coul create a function on the Firebase prototype.

Firebase.prototype.pushWithId = function pushWithid(data) {
  var childRef = this.push();
  data.key = childRef.key();
  childRef.update(data); // or .set() depending on your case
  return childRef;
};

var ref = new Firebase('<my-firebase-app>');
ref.pushWithId({ name: 'Alice' });

请小心修改不属于您的函数的原型。在这种情况下,你可能会好起来的。这个方法没什么用处,而且Firebase SDK获得 .pushWithId()方法的机会并不多。

Take caution with modifying the prototype of functions you do not own. In this case, you'll likely be fine. This method does little, and there's not much of a chance that the Firebase SDK gains a .pushWithId() method.

这篇关于当使用.push方法时,我可以写一个id的副本给对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆