首页 > 代码库 > 【HH原创】Firebase 相关操作及代码示例

【HH原创】Firebase 相关操作及代码示例

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

 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 =http://www.mamicode.com/ 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 diff
25 
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: 
});

 

【HH原创】Firebase 相关操作及代码示例