make an algorithm for friends posts?

Issue

I am creating an api with nestjs and mongodb, a social network, now I am creating a route called "get posts", it is used to get the posts of the friends of the user who makes the request, my doubt is that it does not return the posts of my friends in chronological order

async friendsP(id: string) {
const user = await this.userModel
  .findById(id, {
    _id: false,
    friends: true,
  })
  .catch(() => {
    throw new HttpException('User not found', 404);
  });

// If the id has the same characters as the normal id but does not exist
if (!user) {
  throw new HttpException('User not found', 404);
}

const friends = user.friends;
const postsF = [] as Post[];

// This function makes a loop to grab the posts sent to the user and put them in a single json
const postFuntion = (posts: Post[]) => {
  for (const post of posts) {
    postsF.push(post);
  }
};

// If there are friends
if (friends) {
  for (const idF of friends) {
    const posts = await this.postModel
      .find({ userId: idF })
      .populate('userId', {
        _id: 0,
        nickName: 1,
      });
    postFuntion(posts);
  }
}

return postsF}

What the postman returns to me

Sorry for not zooming, only if I zoom the json would not be seen in its entirety

The problem is that it doesn’t order them in chronological order, I would like them to put the new posts on top, but I don’t know how, can someone help me, please?

I want to mention that the current time in my country is 11:37

I tried to do a sort to postsF, but I get this error

This is the schema of the post, maybe there is something wrong…

export type PostDocument = Post & Document;

type Image = {
  url?: string;
  public_id?: string;
};

 @Schema()
export class Post {
  @Prop({
    type: [{ type: MongooseSchema.Types.ObjectId, ref: 'User' }],
  })
  userId: User;

  @Prop({ type: Object, default: {} })
  image: Image;

  @Prop({ trim: true, default: '' })
  description?: string;

  @Prop({})
  date: string;
}

export const PostSchema = SchemaFactory.createForClass(Post);

Solution

Here is a some code you can use to reorder the result posts array in chronological order by date:

function sortPosts(posts: Post[]) {
  const prefixYMD = "1970-01-01 ";
  posts.sort((post1, post2) => new Date(prefixYMD + post1.date) - new Date(prefixYMD + post2.date));
}

Because your dates operate in hour – minute – second format, you will need to prepend a prefix for a year – month – date, which can ultimately be any date.

Important to note that .sort mutates the original array, hence if you want – you can use it before assigning the posts to postsF, or use it on postsF. You can pretty much tailor this to how you want.

Answered By – Ovidijus Parsiunas

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.