search
HomeWeb Front-endJS TutorialFirebase related operations and code examples
Firebase related operations and code examplesJun 27, 2017 am 09:15 AM
firebasecodeOriginaloperateRelated

Today we need to add the deletion function to Firebase. The code is simplified as follows:

 1 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  9 10 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 modification node:

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 listening:

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; // nullvar 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();  // truevar b = snapshot.child("name").exists(); // truevar c = snapshot.child("name/first").exists(); // truevar 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(); // truevar b = snapshot.child("name").hasChildren(); // truevar 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

>> 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);
});

……

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

Statement
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
五个方便好用的Python自动化脚本五个方便好用的Python自动化脚本Apr 11, 2023 pm 07:31 PM

相比大家都听过自动化生产线、自动化办公等词汇,在没有人工干预的情况下,机器可以自己完成各项任务,这大大提升了工作效率。编程世界里有各种各样的自动化脚本,来完成不同的任务。尤其Python非常适合编写自动化脚本,因为它语法简洁易懂,而且有丰富的第三方工具库。这次我们使用Python来实现几个自动化场景,或许可以用到你的工作中。1、自动化阅读网页新闻这个脚本能够实现从网页中抓取文本,然后自动化语音朗读,当你想听新闻的时候,这是个不错的选择。代码分为两大部分,第一通过爬虫抓取网页文本呢,第二通过阅读工

通过 Firebase Cloud Firestore 实现 PHP 安全验证通过 Firebase Cloud Firestore 实现 PHP 安全验证Jul 25, 2023 pm 10:48 PM

通过FirebaseCloudFirestore实现PHP安全验证FirebaseCloudFirestore是一个灵活且可扩展的云端数据库解决方案,可以用于开发和托管移动端、Web端以及服务器端应用程序。在PHP应用程序中使用FirebaseCloudFirestore进行安全验证可以保护用户数据的安全性。本文将介绍如何使用

用Python写了个小工具,再复杂的文件夹,分分钟帮你整理!用Python写了个小工具,再复杂的文件夹,分分钟帮你整理!Apr 11, 2023 pm 08:19 PM

糟透了我承认我不是一个爱整理桌面的人,因为我觉得乱糟糟的桌面,反而容易找到文件。哈哈,可是最近桌面实在是太乱了,自己都看不下去了,几乎占满了整个屏幕。虽然一键整理桌面的软件很多,但是对于其他路径下的文件,我同样需要整理,于是我想到使用Python,完成这个需求。效果展示我一共为将文件分为9个大类,分别是图片、视频、音频、文档、压缩文件、常用格式、程序脚本、可执行程序和字体文件。# 不同文件组成的嵌套字典 file_dict = { '图片': ['jpg','png','gif','webp

如何使用PHP和Firebase进行实时数据同步如何使用PHP和Firebase进行实时数据同步May 11, 2023 pm 03:54 PM

随着互联网的发展,Web应用程序的复杂性和用户数目的增加,对于实时数据同步的要求也越来越高。Firebase是一种实时数据库,提供了简单易用的API和功能,可以与多种编程语言进行交互。作为一种流行的编程语言,PHP也有很多开发人员使用。在这篇文章里,我们将为您介绍如何使用PHP和Firebase进行实时数据同步。注册Firebase在开始使用Firebas

如何使用PHP和FireBase实现云端数据管理如何使用PHP和FireBase实现云端数据管理Jun 25, 2023 pm 08:48 PM

随着互联网的快速发展,云端数据管理已成为越来越多企业和个人的必备工具。而PHP和Firebase无疑是两个非常强大的工具,可以帮助我们实现云端数据管理。接下来,本文将会介绍如何使用PHP和Firebase实现云端数据管理。什么是FirebaseFirebase是一个由Google提供的云服务平台,旨在帮助开发人员快速构建出高质量、高可靠性的Web应用程序。F

从头开始构建,DeepMind新论文用伪代码详解Transformer从头开始构建,DeepMind新论文用伪代码详解TransformerApr 09, 2023 pm 08:31 PM

2017 年 Transformer 横空出世,由谷歌在论文《Attention is all you need》中引入。这篇论文抛弃了以往深度学习任务里面使用到的 CNN 和 RNN。这一开创性的研究颠覆了以往序列建模和 RNN 划等号的思路,如今被广泛用于 NLP。大热的 GPT、BERT 等都是基于 Transformer 构建的。Transformer 自推出以来,研究者已经提出了许多变体。但大家对 Transformer 的描述似乎都是以口头形式、图形解释等方式介绍该架构。关于 Tra

使用 Firebase Phone Authentication 实现 PHP 安全验证使用 Firebase Phone Authentication 实现 PHP 安全验证Jul 25, 2023 pm 01:07 PM

使用FirebasePhoneAuthentication实现PHP安全验证概述:在开发web应用程序时,安全验证是一个非常重要的环节。为了确保用户的身份和数据安全,我们需要在用户登录或执行敏感操作时进行验证。FirebasePhoneAuthentication是一种强大的身份验证解决方案,它可以帮助我们实现手机号码验证。本文将介绍如何使用

Python-master,实用Python脚本合集!Python-master,实用Python脚本合集!Apr 11, 2023 pm 05:04 PM

Python这门语言很适合用来写些实用的小脚本,跑个自动化、爬虫、算法什么的,非常方便。这也是很多人学习Python的乐趣所在,可能只需要花个礼拜入门语法,就能用第三方库去解决实际问题。我在Github上就看到过不少Python代码的项目,几十行代码就能实现一个场景功能,非常实用。比方说仓库Python-master里就有很多不错的实用Python脚本,举几个简单例子:1. 创建二维码import pyqrcode import png from pyqrcode import QRCode

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool