简体   繁体   中英

How can I return ordered data from Firebase database with Node.js using the firebase-admin module?

I'm trying to query Firebase database to get data ordered by timestamp.

1: This works but the data returned is not ordered by timestamp:

router.get('/articles', function(req, res, next) {
    admin.database().ref('articles').orderByChild('timestamp').once('value').then(function (snapshot) {
        let articles = snapshot.val();
        console.log(articles);
        res.render('articles', articles);
    });
});

2: This returns me the data ordered by timestamp like I want (I can see it in the console.log), but I get this error:

// /node_modules/express/lib/response.js:1003
//   if (err) return req.next(err);
//                      ^
// TypeError: req.next is not a function

router.get('/articles', function(req, res, next) {
    admin.database().ref('articles').orderByChild('timestamp').on('child_added', function (snapshot) {
        let articles = snapshot.val();
        console.log(articles);
        res.render('articles', articles);
    });
});

I don't get what I'm doing wrong. I see that the two firebase database calls are different, one is an once and then (so it must be a promise..?) and the other is a on (so i suppose it's just a normal callback...).

Do you have any idea on why is happening here? Sorry if this is obvious but I'm somewhat of a beginner..

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So in your first example snapshot holds they things: the keys of the matching nodes, their values, and the ordering between them. When you call snapshot.val() this data is converted into a regular JSON object, which doesn't have space for all three pieces of information. At this point the ordering information is dropped.

The solution is to use snapshot.forEach() to loop over the matching nodes in the correct order.

admin.database().ref('articles').orderByChild('timestamp').once('value').then(function (snapshot) {
  var articles = [];
  snapshot.forEach(function(articleSnapshot)
    articles.push(snapshot.val());
  });
  console.log(articles);
  res.render('articles', articles);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM