简体   繁体   中英

How to get only one element from an array (firebase database, nodejs)

If I use limitToLast(1) , then I still get an object, with one key-value pair. To get the value, I use this code:

db.ref('/myarray').limitToLast(1).once('value').then(function(snapshot) {

    var result = snapshot.val();
    var lastElem;
    var lastKey;

    for(var i in result) {
        lastElem= result[i];
        lastKey = i;
        break;
    }

    ...

});

It works, but I think I do it wrong. But haven't found any better solution in the docs. How should I load only one element?

The database looks like this: 排列

When using Firebase queries to get children, use the "child_added" event:

db.ref("/myarray")
  .orderByKey() // order by chlidren's keys
  .limitToLast(1) // only get the last child
  .once("child_added", function(snapshot) {
    var key = snapshot.key;
    var val = snapshot.val();
    ...
  });

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