Firestore: How can I reorder a collection to which I already have a link?

Is there a way to keep the link in the same collection, but reorder it with firestore?

TL; DR: This is similar to the functionality that I am trying to achieve: https://stackoverflow.com/a/1662616/169/121 , but since my data is received from firestore, I do not quite understand the correct way to do this dynamically.


Say I have messagesService.tsone that contains a collection of messages and a link to an Observable message:

messagesCollection: AngularFirestoreCollection<Message>
messages: Observable<Message[]>;

this.messagesCollection = this.db.collection('messages', ref => {
  return ref.orderBy('dateCreated', 'desc');
});

this.messages= this.messagesCollection.valueChanges();

When I insert this data into *ngFor="let message of messages | async", it displays the most recent posts on top, as expected.

Where do I need help:

( , firestore). , , , , , .. , ? , ?

- :

sortMessagesBy(field) {
    this.messagesCollection = this.db.collection('messages', ref => {
          return ref.orderBy(field, 'desc');
    });
}

, , , , .

, :

sortMessagesBy(field) {
    this.messagesCollection = this.db.collection('messages', ref => {
          return ref.orderBy(field, 'desc');
    });
    this.messages= this.messagesCollection.valueChanges();
    return this.messages;
}

, , this.messages, ngFor ( trackBy).

,, , , where IE:

this.messagesCollection = this.db.collection('messages', ref => {
      return ref.where("type", "==", "todo").orderBy(field, 'desc');
});

, , , .

+3
2

@Frank van Puffelen , - , , , :

getMessages(type=null, field=null, direction=null) {
  console.log("sorting messages by: ", type, field, direction);
  this.messagesCollection = this.db.collection('messages', ref => {
    if (type && field) {
      return ref.where('typeId', '==', type).orderBy(field, direction? direction : 'desc');
    } else if (type && !field && !direction) {
      return ref.where('typeId', '==', type)
    } else if (!type && field) {
      return ref.orderBy(field, direction? direction : 'desc');
    } else {
      return ref;
    }
  });
  this.messages = this.messagesCollection.valueChanges();
  return this.messages;
}

, , , . , , :

this.messages = this.messageService.getMessages(this.type, 'views');

:

this.messages = this.messageService.getMessages(null, 'dateCreated');

: typeId , (views, dateCreated, ..), Firebase .

, , , this.messages, * ngFor. , , , trackBy.

:

( async ngFor), . MessageComponent.ts:

this.messageService.getMessages(this.type).subscribe(res => this.messages = res);  
+1

, AngularFirestoreCollection . , .

Firebase SDK.

ref.where("type", "==", "todo").orderBy(field, 'desc')

Query, . , AngularFirestoreCollection.

+3

Source: https://habr.com/ru/post/1654226/


All Articles