AngularFire向Firebase添加数据:如何不生成唯一键写入?
Hey Alex, I see the issue you're facing—using $add is causing Firebase to auto-generate a unique key, which isn't what you want. Let's fix that!
Why $add Creates a Unique Key
The $add method is specifically designed for FirebaseArray instances to add items to a list, which is why it automatically generates a unique push ID. If you want to set data directly at a specific path without that auto-generated key, you need to use different methods.
Solution 1: Update or Set Data Directly on the Reference
Your newRef points directly to the user's node (users/5QMI4UsOeAXZUxxkuy5jozcrrSK2). To add the email field directly under this node (no extra unique key), use either $update or $set:
Using $update (preserves existing data, adds/updates the email field)
var userRef = GetArrayFactory('users', firebaseUser.uid); // Reference to the user's node userRef.$update({ 'email': email }).then(function() { console.log("User email successfully added/updated!"); }).catch(function(error) { console.error("Error updating email:", error); });
Using $set (replaces the entire node content with the new data)
Use this if you want to overwrite all existing data under the user's node with just the email:
var userRef = GetArrayFactory('users', firebaseUser.uid); userRef.$set({ 'email': email }).then(function() { console.log("User data successfully set!"); }).catch(function(error) { console.error("Error setting user data:", error); });
Solution 2: Add Data Under a Custom Key
If you want to store the email under a specific custom key (instead of auto-generated), you can create a child reference and use $set:
var userRef = GetArrayFactory('users', firebaseUser.uid); var customKeyRef = userRef.child('user_email'); // Your custom key customKeyRef.$set(email).then(function() { console.log("Email added under custom key 'user_email'!"); });
Key Takeaway
$add= for list items with auto-generated push IDs$update/$set= for setting data directly at a specific path (no auto-generated keys)
内容的提问来源于stack exchange,提问作者Alex Crowel

