Example code for Firebase related operations

零下一度
Release: 2017-06-28 10:55:36
Original
1459 people have browsed it

今天需要对 Firebase 增加删除功能,代码精简如下:

var admin = require('firebase-admin'); 2 var config = require('./config.json'); 3 4 var defaultAppConfig = { 5 credential: admin.credential.cert(config.firebase.cert), 6 databaseURL: config.firebase.databaseURL 7 }; 8
var defaultAppName = 'GoPeople-NodeJS-Admin';11 var defaultApp = admin.initializeApp(defaultAppConfig, defaultAppName);12 13 var signaturesRef = defaultApp.database().ref('signatures');14 15 signaturesRef.orderByChild("isChecked").equalTo(true).limitToLast(10).once("value")16 .then(function(snapshot) {17 18 snapshot.forEach(function(childSnapshot) {19 var key = childSnapshot.key;20 var childData = childSnapshot.val();21 22 var now = new Date();23 var date = new Date(childData.date);24 var dayDiff = parseInt((now - date) / (1000 * 60 * 60 * 24)); // day diff25 26 if(dayDiff >30){27 signaturesRef.child(key).remove(function(error) {28 console.log(key);29 console.log(dayDiff);30 console.log(error ? ("Uh oh! " + error) : "Success!");31 });32 }else{33 console.log(key);34 console.log(dayDiff);35 }36 });37 38 });


Firebase 修改节点:

function finishJobSync(jobGuid) { var signaturesRef = defaultApp.database().ref('signatures').child(jobGuid);
signaturesRef.update({isChecked: true},function(error) { if (error) {
logger.error(error);
} else {
logger.info('Job ' + jobGuid + ' signature has been synced.');
}
});
}

Firebase 监听:

var signaturesRef = defaultApp.database().ref('signatures');

signaturesRef.orderByChild("isChecked").equalTo(false).on("child_added", function(snapshot, prevChildKey) { // TODO: });

admin.database.DataSnapshot

>> key


// Assume we have the following data in the Database:{ "name": { "first": "Ada", "last": "Lovelace"
}
}var ref = admin.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) { var key = snapshot.key; // "ada"
var childKey = snapshot.child("name/last").key; // "last"
});


>> child

var rootRef = admin.database().ref();
rootRef.once("value")
.then(function(snapshot) { var key = snapshot.key; // null
var childKey = snapshot.child("users/ada").key; // "ada"
});

>> exists


// Assume we have the following data in the Database:{ "name": { "first": "Ada", "last": "Lovelace"
}
}// Test for the existence of certain keys within a DataSnapshotvar ref = admin.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) { var a = snapshot.exists(); // true
var b = snapshot.child("name").exists(); // true
var c = snapshot.child("name/first").exists(); // true
var d = snapshot.child("name/middle").exists(); // false
});


>> foreach


// Assume we have the following data in the Database:{ "users": { "ada": { "first": "Ada", "last": "Lovelace"
}, "alan": { "first": "Alan", "last": "Turing"
}
}
}// Loop through users in order with the forEach() method. The callback// provided to forEach() will be called synchronously with a DataSnapshot// for each child:var query = admin.database().ref("users").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) { // key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key; // childData will be the actual contents of the child
var childData = childSnapshot.val();
});
});


>> hasChildren


// Assume we have the following data in the Database:{ "name": { "first": "Ada", "last": "Lovelace"
}
}var ref = admin.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) { var a = snapshot.hasChildren(); // true
var b = snapshot.child("name").hasChildren(); // true
var c = snapshot.child("name/first").hasChildren(); // false
});


>> numChildren


// Assume we have the following data in the Database:{ "name": { "first": "Ada", "last": "Lovelace"
}
}var ref = admin.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) { var a = snapshot.numChildren(); // 1 ("name")
var b = snapshot.child("name").numChildren(); // 2 ("first", "last")
var c = snapshot.child("name/first").numChildren(); // 0
});

admin.database.Query

>> orderByChild

var ref = admin.database().ref("dinosaurs");
ref.orderByChild("height").on("child_added", function(snapshot) {
console.log(snapshot.key + " was " + snapshot.val().height + " m tall");
});

>> orderByKey

var ref = admin.database().ref("dinosaurs");
ref.orderByKey().on("child_added", function(snapshot) {
console.log(snapshot.key);
});

>> orderByValue

var scoresRef = admin.database().ref("scores");
scoresRef.orderByValue().limitToLast(3).on("value", function(snapshot) {
snapshot.forEach(function(data) {
console.log("The " + data.key + " score is " + data.val());
});
});

>> startAt, endAt


// Find all dinosaurs that are at least three meters tall.var ref = admin.database().ref("dinosaurs");
ref.orderByChild("height").startAt(3).on("child_added", function(snapshot) {
console.log(snapshot.key)
});// Find all dinosaurs whose names come before Pterodactyl lexicographically.var ref = admin.database().ref("dinosaurs");
ref.orderByKey().endAt("pterodactyl").on("child_added", function(snapshot) {
console.log(snapshot.key);
});


>> limitToFirst, limitToLast


// Find the two shortest dinosaurs.var ref = admin.database().ref("dinosaurs");
ref.orderByChild("height").limitToFirst(2).on("child_added", function(snapshot) { // This will be called exactly two times (unless there are less than two
// dinosaurs in the Database).

// It will also get fired again if one of the first two dinosaurs is
// removed from the data set, as a new dinosaur will now be the second
// shortest. console.log(snapshot.key);
});// Find the two heaviest dinosaurs.var ref = admin.database().ref("dinosaurs");
ref.orderByChild("weight").limitToLast(2).on("child_added", function(snapshot) { // This callback will be triggered exactly two times, unless there are
// fewer than two dinosaurs stored in the Database. It will also get fired
// for every new, heavier dinosaur that gets added to the data set. console.log(snapshot.key);
});


>> equalTo

// Find all dinosaurs whose height is exactly 25 meters.var ref = admin.database().ref("dinosaurs");
ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
console.log(snapshot.key);
});

>> isEqual

var rootRef = admin.database().ref();var usersRef = rootRef.child("users");

usersRef.isEqual(rootRef); // falseusersRef.isEqual(rootRef.child("users")); // trueusersRef.parent.isEqual(rootRef); // true


var rootRef = admin.database().ref();var usersRef = rootRef.child("users");var usersQuery = usersRef.limitToLast(10);

usersQuery.isEqual(usersRef); // falseusersQuery.isEqual(usersRef.limitToLast(10)); // trueusersQuery.isEqual(rootRef.limitToLast(10)); // falseusersQuery.isEqual(usersRef.orderByKey().limitToLast(10)); // false


>> toString


// Calling toString() on a root Firebase reference returns the URL where its// data is stored within the Database:var rootRef = admin.database().ref();var rootUrl = rootRef.toString();// rootUrl === "https://sample-app.firebaseio.com/".// Calling toString() at a deeper Firebase reference returns the URL of that// deep path within the Database:var adaRef = rootRef.child('users/ada');var adaURL = adaRef.toString();// adaURL === "https://sample-app.firebaseio.com/users/ada".



The above is the detailed content of Example code for Firebase related operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!