0

0

Firebase相关操作的实例代码

零下一度

零下一度

发布时间:2017-06-28 10:55:36

|

1704人浏览过

|

来源于php中文网

原创

今天需要对 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

台讯电子企业网站管理系统  简繁全功能版
台讯电子企业网站管理系统 简繁全功能版

超级适合代理建设企业站点的企业源码,超方面实用!程序说明: 1.特色:简繁中文切换、产品展示系统、新闻发布系统、会员管理系统、留言本计数器、网站信息统计、强大后台操作 功能等; 2.页面包括:首页、企业介绍、滚动公告通知发布系统、企业新闻系统、产品展示系统、企业案例发布展示系 统、企业招聘信息发布系统、信息资源下载系统、在线定单系统、在线客服系统、在线留言本系统、网站调查投票系统、友情连接系统、会

下载

>> 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".

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

54

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

40

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

50

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

12

2026.01.31

漫画防走失登陆入口大全
漫画防走失登陆入口大全

2026最新漫画防走失登录入口合集,汇总多个稳定可用网址,助你畅享高清无广告漫画阅读体验。阅读专题下面的文章了解更多详细内容。

13

2026.01.31

php多线程怎么实现
php多线程怎么实现

PHP本身不支持原生多线程,但可通过扩展如pthreads、Swoole或结合多进程、协程等方式实现并发处理。阅读专题下面的文章了解更多详细内容。

1

2026.01.31

php如何运行环境
php如何运行环境

本合集详细介绍PHP运行环境的搭建与配置方法,涵盖Windows、Linux及Mac系统下的安装步骤、常见问题及解决方案。阅读专题下面的文章了解更多详细内容。

0

2026.01.31

php环境变量如何设置
php环境变量如何设置

本合集详细讲解PHP环境变量的设置方法,涵盖Windows、Linux及常见服务器环境配置技巧,助你快速掌握环境变量的正确配置。阅读专题下面的文章了解更多详细内容。

0

2026.01.31

php图片如何上传
php图片如何上传

本合集涵盖PHP图片上传的核心方法、安全处理及常见问题解决方案,适合初学者与进阶开发者。阅读专题下面的文章了解更多详细内容。

2

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Node.js 教程
Node.js 教程

共57课时 | 9.9万人学习

ASP 教程
ASP 教程

共34课时 | 4.3万人学习

Python 教程
Python 教程

共137课时 | 7.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号