0

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
  • https://stackoverflow.com/questions/5073799/how-to-sort-a-javascript-array-of-objects-by-nested-object-property – Marc Jun 30 '19 at 03:25
  • @Marc I am unsure if that works for me. I tried to make it work but despite the changes I make I cant get the snapshot to be the proper datatype and I cant get rid of errors like: Parameter 'a' implicitly has an 'any' type.ts(7006) –  Jun 30 '19 at 03:34

1 Answers1

0

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807