[英]Update realtime database in Firebase
I am creating a API which can update value from realtime database (Firebase). 我正在创建一个API,可以从实时数据库(Firebase)更新值。 Using ClaudiaJS to create API. 使用ClaudiaJS创建API。 Basically, API will update the number of student of a class by year. 基本上,API会按年更新班级的学生人数。
What I have done: 我做了什么:
Realtime Database (Firebase) 实时数据库(Firebase)
class
|__2015
| |__numberOfStudent: 50
|__2016
|__numberOfStudent: 60
Export to JSON like this: 像这样导出为JSON:
{
"class": {
"2015": {
"numberOfStudent": 50
},
"2016": {
"numberOfStudent": 60
}
}
}
Javascript file (ClaudiaJS): Javascript文件(ClaudiaJS):
var ApiBuilder = require('claudia-api-builder');
api = new ApiBuilder();
module.exports = api;
var admin = require("firebase-admin");
var serviceAccount = require("./xxxxxxx-firebase-adminsdk-nxxxxx.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxxx.firebaseio.com"
});
api.post('/addmore/{year}/{number}', function (request) {
var database = admin.database().ref('class');
//Params
var year = request.pathParams.year;
var number = request.pathParams.number;
var ref = year + '/numberOfStudent'; // '2015/numberOfStudent'
database.update({
ref : parseInt(number) // "2015/numberOfStudent" : 60
});
return 'Update successfully';
});
When I run the api in Postman: 当我在邮递员中运行api时:
http://xxxxapi.com/addmore/2015/55 http://xxxxapi.com/addmore/2015/55
What happened: API replied 'Update successfully', but the database didn't get any update. 发生了什么:API答复“更新成功”,但数据库未获得任何更新。 It seems that the code database.update() doesn't work at all. 似乎代码database.update()根本不起作用。
Any suggestion is very appreciated 任何建议都非常感谢
The update
call happens asynchronously, so currently the return
happens before update
completes. update
调用异步发生,因此当前return
发生在update
完成之前。
update
returns a Promise , so try the following: update
返回Promise ,因此请尝试以下操作:
return database.update({ref : parseInt(number)})
.then(() => {
// Each then() should return a value or throw
return 'Update successful';
})
.catch(error => {
// handle the error however you like
console.error(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.