Ad

How Can I Sort A Snapshot Based On A TimeStamp Value Further Down In The Structure?

I get a snapshot returned from the below code. I would like to be able to sort through the returned snapshot by using either the childVal which is a timeStamp.

  const userRef = admin.database().ref('Posts').child(uid)
  const update = userRef.orderByChild('Media/media1/postTimeStamp').once('value')
  .then(snap => {
    var i = 1

    if (snap.exists()) {
      snap.forEach((snapVal) => {
        if (i <= 2) {
          const postID = String(snapVal["key"])
          const postRef = admin.database().ref("Timeline").child(followerUID).child(uid + ":" + postID).child("timeStamp")

          let coredate = new Date().getTime();
          let unixdate = new Date( '2001/01/01' ).getTime();
          let mactimestamp = ( coredate-unixdate )/1000;

          postRef.set(mactimestamp)//update

I tried doing something like:

let array = (snap.val).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) //but this gets an error (cant be done)

The goal is to be able to loop through this array of posts in accending order.

"Posts" : {
"uid" : {
  "post:583541341" : {
    "Media" : {
      "postTime" : {
        "postTimeStamp" : 5.83541341963183E8
Ad

Answer

You can get all posts for a given user ordered by timestamp with:

const userRef = admin.database().ref('Posts').child(uid)
userRef.orderByChild('Media/postTime/postTimeStamp').once('value')
.then(snap => {
  snap.forEach((snapshot) => {
    console.log(snapshot.key);
  });
});

Since the path Media/postTime/postTimeStamp exists under each child node, the database can order on that property's value.

Ad
source: stackoverflow.com
Ad